dpppstl
dpppstl

Reputation: 31

Accessing values from dictionaries nested in a list

First question here!

countries = [{'country': 'Italy', 'size':3,'reg':9},
             {'country': 'Germany', 'size':7,'reg':1},
             {'country': 'USA', 'size':9,'reg':4},
            ]

weights = {'size' : 100, 'reg' : 30}

I am trying to multiply values from the 'countries' nested dictionaries with the value associated with the matching key in the 'weights' dictionary. I tried a for loop approach as the values in 'weights' will be updated by the user.

I have tried this:

countries_weighted = copy.deepcopy(countries)

for key in weights.items():
        for i in countries_weighted:
           countries_weighted[i][key] *= weights[key]

That doesn't seem to work:

-
TypeError                                 Traceback (most recent call last)
<ipython-input-52-9753dabe7648> in <module>()
     13 for key in weights.items():
     14     for i in countries_weighted:
---> 15        countries_weighted[i][key] *= weights[key]
     16 

TypeError: list indices must be integers or slices, not dict

Any idea? Thanks in advance.

Upvotes: 0

Views: 60

Answers (3)

Saul Meng
Saul Meng

Reputation: 61

Only need to write countries_weighted[i][key] *= weights[key] as i[key] *= weights[key].

Upvotes: 0

Est
Est

Reputation: 420

You could do it like this:

countries = [{'country': 'Italy', 'size':3,'reg':9},
             {'country': 'Germany', 'size':7,'reg':1},
             {'country': 'USA', 'size':9,'reg':4},
            ]

weights = {'size' : 100, 'reg' : 30}

for country in countries:
    for key in weights.keys():
        country[key] *= weights[key]

print(countries)

Upvotes: 2

jpp
jpp

Reputation: 164623

There are a couple of issues:

  1. dict.items cycles key-value pairs, not just keys;
  2. when you iterate countries_weighted you should use i.

So you can amend as follows:

for key, value in weights.items():
    for i in countries_weighted:
        i[key] *= value

Upvotes: 0

Related Questions