I have multiple dictionaries with different data for each country as a key:
countries = {'Portugal', 'US'}
score = {'Portugal': 88.0, 'US': 86.20}
year = {'Portugal': 2014, 'US': 2013 }
price ={'Portugal': 26.77, 'US': 36.58 }
I want to create a nested dictionary with country as a key and inside add key value pairs for each countries data in each dict.
I make two dictionaries with countries as the keys, and the keys for each dictionary
dd = {key: None for key in countries}
d_temp = dict.fromkeys(["Variety","Year","Price","Points","Adjective"])
for c in countries:
d_temp['Variety'] = d1[c]
d_temp['Year'] = d2[c]
d_temp['Price'] = d3[c]
d_temp['Points'] = d4[c]
d_temp['Adjective'] = d5[c]
dd[c] = d_temp
But after each iteration it updates every value for each previous country
CodePudding user response:
This will deliver {'Portugal': {'Variety': 88.0, 'Year': 2014, 'Price': 26.77}, 'US': {'Variety': 86.2, 'Year': 2013, 'Price': 36.58}}
countries = {'Portugal', 'US'}
score = {'Portugal': 88.0, 'US': 86.20}
year = {'Portugal': 2014, 'US': 2013}
price = {'Portugal': 26.77, 'US': 36.58}
dd = {key: None for key in countries}
for c in countries:
d_temp = {}
d_temp['Variety'] = score[c]
d_temp['Year'] = year[c]
d_temp['Price'] = price[c]
dd[c] = d_temp
print(dd)
Your problem is that you are creating a reference to the same dictionary (d_temp) on every country key. This means every country shares the same nested dictionary (d_temp). That´s what you see as "updating" of the country sub-dictionary.
CodePudding user response:
You can use dict comprehension:
countries = {'Portugal', 'US'}
score = {'Portugal': 88.0, 'US': 86.20}
year = {'Portugal': 2014, 'US': 2013}
price = {'Portugal': 26.77, 'US': 36.58}
key_to_dict = {'score': score, 'year': year, 'price': price}
output = {country: {k: d[country] for k, d in key_to_dict.items()} for country in countries}
print(output)
# {'US': {'score': 86.2, 'year': 2013, 'price': 36.58}, 'Portugal': {'score': 88.0, 'year': 2014, 'price': 26.77}}