python有道字典_在python中搜索字典列表

1586010002-jmsa.png

I have a list of dictionaries and I want to find if a value exits in the list and if it exists return the dictionary.

For example

Mylist= [{'Stringa': "ABC",

'Stringb': "DE",

'val': 5},

{'Stringa': "DEF",

'Stringb': "GHI",

'val': 6}]

I want to find if for any dictionary

dict["stringa"]=="ABC". If yes return the corresponding dictionary.

I used the function "any"

any(d['Stringa'] == 'ABC' for d in Mylist)

but it just gives True/False. How can I get the corresponding dictionary.

解决方案

any will just check if any of the items in the iterable satisfy the condition or not. It cannot be used to retrieve matching items.

Use a list comprehension to get the list of matched items, like this

matches = [d for d in Mylist if d['Stringa'] == 'ABC']

This will iterate through the list of dictionaries and whenever it finds a match, it will include that in the result list. And then you can access the actual dictionary with its index in the list, like matches[0].

Alternatively, you can use a generator expression, like this

matches = (d for d in Mylist if d['Stringa'] == 'ABC')

and you can get the next matched item from the list, with

actual_dict = next(matches)

This will give you the actual dictionary. If you want to get the next matched item, you can call next with the generator expression again. If you want to get all the matching items at once, as a list, you can simply do

list_of_matches = list(matches)

Note: Calling next() will raise an exception, if there are no more items to be retrieved from the generator. So, you can pass a default value to be returned.

actual_dict = next(matches, None)

Now, actual_dict will be None if the generator is exhausted.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值