0

PHP Code:

<?php

$result = [];

$input = ['Sofia 50', 'Sofia 20', 'Sofia 30', 'Varna 10', 'Varna 20'];

foreach ($input as $item) {
    $keyValuePairs = explode(' ', $item);
    $key = $keyValuePairs[0];
    $value = $keyValuePairs[1];
    if (array_key_exists($key, $result)) {
        $result[$key]['count'] += 1;
        $result[$key]['sum'] += $value;
    } else {
        $result[$key]['count'] = 1;
        $result[$key]['sum'] = $value;
    }
}

echo '<pre>';
var_dump($result);

What I tried in Python:

input_row = input_row.split(' ')
region_name = input_row[0]
region_size = input_row[1]

if region_name in result:
    result[region_name]['count'] += 1
    result[region_name]['sum'] += region_size
else:
    result[region_name]['count'] = 1
    result[region_name]['sum'] = region_size

But it doesn't work in Python.

What result I expect:

array(2) {
  ["Sofia"]=>
  array(2) {
    ["count"]=>
    int(3)
    ["sum"]=>
    int(100)
  }
  ["Varna"]=>
  array(2) {
    ["count"]=>
    int(2)
    ["sum"]=>
    int(30)
  }
}
7
  • Did you explain what you are actually trying to do? Commented May 15, 2019 at 10:18
  • @Austin Sure, it's edited. Commented May 15, 2019 at 10:19
  • No loop in your python code makes it a bit suspect... what is input_row there? Commented May 15, 2019 at 10:19
  • 1
    Your Python code would work if you initialize the region name dictionary in your else statement first: else: result[region_name] = {}; result[region_name]['count'] = 1 etc. Commented May 15, 2019 at 10:22
  • @ViktorPetrov Hmm, yeah, you are right, but why thix syntax, doesn't work result[region_name]['count'] = 1 Commented May 15, 2019 at 10:25

1 Answer 1

3

PHP to Python

input_data = ['Sofia 50', 'Sofia 20', 'Sofia 30', 'Varna 10', 'Varna 20']
result = {}

for elem in input_data:                     #Iterate each element. 
    key, value = elem.split()               #Split on space
    if key not in result:                   #Check if key exists in result
        result[key] = {'count': 0,'sum': 0}
    result[key]['count'] += 1                #Increment count
    result[key]['sum'] += int(value)         #Increment value

print(result)

Output:

{'Sofia': {'count': 3, 'sum': 100}, 'Varna': {'count': 2, 'sum': 30}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.