迭代字典列表 [英] Iterating over list of dictionaries

查看:51
本文介绍了迭代字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 -myList - 其中每个元素都是一个字典.我希望遍历这个列表,但我每次只对每个字典中的一个属性 - 'age' 感兴趣.我也对计算迭代次数感兴趣.

I have a list -myList - where each element is a dictionary. I wish to iterate over this list but I am only interesting in one attribute - 'age' - in each dictionary each time. I am also interested in keeping count of the number of iterations.

我愿意:

for i, entry in enumerate(myList):
    print i;
    print entry['age']; 

但是想知道有没有更pythonic的东西.有什么提示吗?

But was wondering is there something more pythonic. Any tips?

推荐答案

你可以使用生成器来只抓取年龄.

You could use a generator to only grab ages.

# Get a dictionary 
myList = [{'age':x} for x in range(1,10)]

# Enumerate ages
for i, age in enumerate(d['age'] for d in myList): 
    print i,age

而且,是的,不要使用分号.

And, yeah, don't use semicolons.

这篇关于迭代字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆