Python:迭代多个词典

时间:2014-07-07 15:50:24

标签: python python-2.7 dictionary

我有3个列表,每个列表都包含字典。我会得到某些键的值,并希望保存此值的min-Operation结果。以下代码给出了错误:TypeError:list indices必须是整数,而不是dict。

import numpy as np
import itertools


humidity = [{'high': 90, 'middle': 50, 'low': 10}, {'high': 75, 'middle': 40, 'low': 5} ]

temperature =[{'warm': 35, 'normal': 20, 'cold': 5 }, {'warm': 40, 'normal': 18, 'cold': 10 }]

wind = [{'breeze': 25, 'gale': 100}, {'breeze': 20, 'gale': 90}]

results=[]
for h, t, w in itertools.izip(humidity, temperature, wind):

  results.append(np.fmin (humidity[h]['high'], np.fmin( temperature[t]['normal'], wind[w]['breeze']) ) )

但如果我在控制台中写道(Spyder,python 2.7):

 result = np.fmin (humidity[0]['high'], np.fmin( temperature[0]['normal'], wind[0]['breeze']) )

我得到20,这是真的。但为什么我不能遍历整个词典呢?怎么了?

非常感谢您的回答/想法!

1 个答案:

答案 0 :(得分:1)

您需要引用h,t,w个变量而不是原始列表

results.append(np.fmin (h['high'], np.fmin( t['normal'], w['breeze']) ) )

因为h,t,w是从您的zip解压缩的字典,而不是int s所以您不能使用它们来索引列表

视觉上,humidity[h]['high']看起来像

humidity[{'high': 90, 'middle': 50, 'low': 10}]['high']

语法上没有意义