在列表中的字典中标识特定值

2024-06-17 12:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我的目标是识别字典中的long_name值,其中type键的值为'sucere'。在本例中,我希望返回myList中第二个字典中的3

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


1条回答
网友
1楼 · 发布于 2024-06-17 12:46:56

只要把字典翻个遍就行了

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']

相关问题 更多 >