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)
}
}
input_rowthere?else: result[region_name] = {}; result[region_name]['count'] = 1etc.result[region_name]['count'] = 1