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

时间:2018-11-22 16:36:18

标签: python python-3.x list dictionary for-loop

第一个问题!

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循环方法,因为“权重”中的值将由用户更新。

我已经尝试过了:

countries_weighted = copy.deepcopy(countries)

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

这似乎不起作用:

-
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

有什么主意吗?预先感谢。

3 个答案:

答案 0 :(得分:2)

您可以这样做:

ROW: {"Durata ":" 48","UnitàDididattica ":"FISICA - MODULO A - [UD-1]","TipoFormaz. ":"Base","CFU":" 6","TipoAttività ":"LEZ","Settore ":"FIS/01 - FISICA SPERIMENTALE"}
DURATA:  48
ROW: {"Durata ":" 48","CFU ":"6","UnitàDididattica ":"FISICA - MODULO B - [UD-2]","TipoFormaz ":"Base","TipoAttivit à":"LEZ","Settore ":"FIS/01 - FISICA SPERIMENTALE"}
DURATA:  48

答案 1 :(得分:0)

有两个问题:

  1. dict.items循环键值对,而不仅仅是键;
  2. 迭代countries_weighted时,应使用 i

因此您可以进行如下修改:

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

答案 2 :(得分:0)

只需将countries_weighted[i][key] *= weights[key]写为i[key] *= weights[key]