识别列表中字典中的特定值



我目前有一个嵌套在列表中的字典。到目前为止看起来是这样的。。。

mylist = [{'long_name': 1, 'type': 'unsure'}, {'long_name': 3, 'type': 'certain'}, {'long_name': 5, 'type': 'uncertain'}]

我的目标是在字典中识别类型键的值为"certain"的long_name值。在这个例子中,我希望返回myList中第二个字典中的3。

我将有许多不同的列表/dict组合,正确dict的位置在它们之间会有所不同,这就是为什么我需要想出这个解决方案。

只需循环遍历字典!

mylist = [{'long_name': 1, 'type': 'unsure'}, {'long_name': 3, 'type': 'certain'}, {'long_name': 5, 'type': 'uncertain'}]
for item in mylist:
if item['type'] == 'certain':
print(item['long_name']) # Or, add to another list

幻想列表理解(如果你想把它放在列表中(

mylist = [{'long_name': 1, 'type': 'unsure'}, {'long_name': 3, 'type': 'certain'}, {'long_name': 5, 'type': 'uncertain'}]
certain_names = [item['long_name'] for item in mylist if item['type'] == 'certain']

最新更新