python中筛选出列表中的字典,从python中的字典列表中选择一个字段

Lets say I have a list of dictionaries like so:

dictionList = {1: {'Type': 'Cat', 'Legs': 4},

2: {'Type': 'Dog', 'Legs': 4},

3: {'Type': 'Bird', 'Legs': 2}}

Using a for loop I want to iterate through the list until I catch a dictionary with a Type field equal to "Dog".

My best attempt was:

for i in dictionList:

if dictionList(i['Type']) == "Dog":

print "Found dog!"

But that gets me the following error:

TypeError: 'int' object has no attribute '__getitem__'

Any ideas on how to properly do this?

解决方案

Use the values iterator for dictionaries:

for v in dictionList.values():

if v['Type']=='Dog':

print "Found a dog!"

EDIT: I will say though that in your original question you are asking to check the Type of a value in a dictionary, which is somewhat misleading. What you are requesting is the content of a value called 'Type'. This may be a subtle difference to understanding what you want, but it is a rather large difference in terms of programming.

In Python, you should ever only RARELY need to type-check anything.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值