Home > OS >  Assign list values to dictionary values and sum values under keys
Assign list values to dictionary values and sum values under keys

Time:10-28

I want to sum value for each city, and sum values for whole province. Now I can sum the value for each city, but I don't know how to sum values for whole province.

city_value = [["Edinburgh",100],["Manchester",100],["London",100],["Manchester",100]]
province_dict = {"England":["Manchester","London","Exeter"], "Scotland":["Edinburgh","Glasgow","Dundee"]}
# Create a dictionary with city names as key
list2 = []
for i in city_value:
    list2.append(i[0])
dict1 = {i:[] for i in list2}     
print (dict1)
# Assign area into city
for i in list1:
    for keys,values in dict1.items():
        if i[0] == keys :
            values.append(i[1])

dict2 = dict(zip(dict1.keys(), [[sum(item)] for item in dict1.values()]))

print (dict2)

CodePudding user response:

For city, you're iteraring 2 times on the first list to initialize it, then iterate inside another iteration, then finally another time complexity is about O(n² 3n)

Just iterate once to build the city_sum, then build the province one

from collections import defaultdict

city_value = [["Edinburgh", 100], ["Manchester", 100], ["London", 100], ["Manchester", 100]]
province_dict = {"England": ["Manchester", "London", "Exeter"], "Scotland": ["Edinburgh", "Glasgow", "Dundee"]}

city_sum = defaultdict(int)
for city, val in city_value:
    city_sum[city]  = val

province_sum = defaultdict(int)
for province, cities in province_dict.items():
    for city in cities:
        province_sum[province]  = city_sum.get(city, 0)

print(city_sum)      # {'Edinburgh': 100, 'Manchester': 200, 'London': 100}
print(province_sum)  # {'England': 300, 'Scotland': 100}

CodePudding user response:

You can use dictionary comprehension with sum to sum over cities within each province.

city_value = [["Edinburgh",100],["Manchester",100],["London",100],["Manchester",100]]
province_dict = {"England":["Manchester","London","Exeter"], "Scotland":["Edinburgh","Glasgow","Dundee"]}

sum_city = {}
for k, v in city_value:
    sum_city[k] = sum_city.get(k, 0)   v
print(sum_city) # {'Edinburgh': 100, 'Manchester': 200, 'London': 100}

sum_prov = {k: sum(sum_city.get(city, 0) for city in v) for k, v in province_dict.items()}
print(sum_prov) # {'England': 300, 'Scotland': 100}

CodePudding user response:

city_value = [["Edinburgh",111],["Manchester",777],["London",333],["Dundee",444]]
province_dict = {"England":["Manchester","London","Exeter"], "Scotland":["Edinburgh","Glasgow","Dundee"]}
province_total_dict = {}
for key, value in province_dict.items():
    province = []
    for city in value:
        for cv in city_value:
            if cv[0] == city:
                province.append(cv[1])
    province_total_dict[key]= sum(province)
print(province_total_dict)


output; {'England': 1110, 'Scotland': 555}
  • Related