简体   繁体   English

Python:遍历多个字典

[英]Python: Iterating through multiple dictionaries

I've 3 lists, each of them contains dictionaries. 我有3个列表,每个列表都包含字典。 I would get the values for certain keys and want to save the result from the min-Operation of this values. 我将获取某些键的值,并希望保存此值的min-Operation结果。 The following code gives a error: TypeError: list indices must be integers, not dict. 下面的代码给出一个错误:TypeError:列表索引必须是整数,而不是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']) ) )

But if i wrote in the console(Spyder,python 2.7): 但是如果我在控制台中写了(Spyder,python 2.7):

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

I get 20 and it's true. 我得到20,这是真的。 But why can I not iterate over the whole dictionaries? 但是,为什么我不能遍历整个词典呢? What is wrong? 怎么了?

Thank you very much for your answers/ideas! 非常感谢您的回答/想法!

You need to reference your h,t,w variables instead of the original lists 您需要引用您的h,t,w变量而不是原始列表

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

as h,t,w are dictionaries unpacked from your zip, not int s so you can't use them to index a list 因为h,t,w是从zip中解压缩的字典,而不是int所以您不能使用它们来索引列表

Visiually, humidity[h]['high'] looks like 可见, humidity[h]['high']看起来像

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

Which does not make sense syntactically 在语法上没有意义

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

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