Home > Software engineering >  Create a dictionary where the keys are values of dictionaries inside lists in a dictionary and the v
Create a dictionary where the keys are values of dictionaries inside lists in a dictionary and the v

Time:05-06

I have this dictionary of lists of dictionaries (I cannot change the structure for the work):

dict_countries = {'gb': [{'datetime': '1955-10-10 17:00:00', 'city': 'chester'}, 
                         {'datetime': '1974-10-10 23:00:00', 'city': 'chester'}], 
                  'us': [{'datetime': '1955-10-10 17:00:00', 'city': 'hudson'}]
                 }

And the function:

def Seen_in_the_city(dict_countries:dict,)-> dict:
    city_dict = {}
    for each_country in dict_countries.values():   
        for each_sight in each_country: 
            citi = each_sight["city"]
            if citi in city_dict.keys():
                city_dict[each_sight["city"]] = 1 
            else:
                city_dict[citi] = 1        
    return city_dict

I get:

{'chester': 1,'hudson': 1}

instead of

{'chester': 2,'hudson': 1}

CodePudding user response:

You can try using Counter (a subclass of dict) from the collections module in the Python Standard Library:

from collections import Counter
c = Counter()
for key in dict_countries:
    for d in dict_countries[key]:
        c.update(v for k, v in d.items() if k == 'city')
        
print(c)

Output

Counter({'chester': 2, 'hudson': 1})

CodePudding user response:

Try:

output = dict()
for country, cities in dict_countries.items():
    for city in cities:
        if city["city"] not in output:
            output[city["city"]] = 0
        output[city["city"]]  = 1

CodePudding user response:

You don't need to say 1 in order to add a positive number. Also in the if citi statement, = 1 means adding 1 to the existing value (1 1) where as = 1 is basically saying giving it a value of 1 once again.

if citi in city_dict.keys():
    city_dict[each_sight["city"]]  =1 
else:
    city_dict[citi] = 1

CodePudding user response:

You can use groupby from itertools

from itertools import groupby
print({i: len(list(j)[0])  for i,j in groupby(dict_countries.values(), key=lambda x: x[0]["city"])})

CodePudding user response:

If you don't want additional imports (not that you shouldn't use Counter) here's another way:

dict_countries = {'gb': [{'datetime': '1955-10-10 17:00:00', 'city': 'chester'}, 
                         {'datetime': '1974-10-10 23:00:00', 'city': 'chester'}], 
                  'us': [{'datetime': '1955-10-10 17:00:00', 'city': 'hudson'}]
                 }

def Seen_in_the_city(dict_countries:dict,)-> dict:
    city_dict = {}
    for each_country in dict_countries.values():   
        for each_sight in each_country: 
            citi = each_sight["city"]
            city_dict[citi] = city_dict.get(citi, 0)   1       
    return city_dict

print(Seen_in_the_city(dict_countries))
  • Related