简体   繁体   English

从嵌套在列表中的字典访问值

[英]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. 我尝试了for循环方法,因为“权重”中的值将由用户更新。

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. 提前致谢。

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)

There are a couple of issues: 有几个问题:

  1. dict.items cycles key-value pairs, not just keys; dict.items循环键值对,而不仅仅是键;
  2. when you iterate countries_weighted you should use i . 当你迭代countries_weighted你应该使用 i

So you can amend as follows: 因此,您可以进行如下修改:

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

只需要将country_weighted countries_weighted[i][key] *= weights[key]i[key] *= weights[key]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM