如何在字典列表中查找字典某个值是否为特定值

0 投票
4 回答
50 浏览
提问于 2025-04-14 18:13

这是我的列表:

list1 = [
    {'id': 1, 'custom': 'one'},
    {'id': 2, 'custom': 'two'},
    {'id': 3, 'custom': 'one'},
    {'id': 1, 'custom': 'two'},
    {'id': 3, 'custom': 'two'},
    {'id': 4, 'custom': 'one'},
    {'id': 5, 'custom': 'two'},
]

我想找出哪些 id 只有 custom 值为 two。如果它们有 one 或者同时有 onetwo,那也没问题。问题在于那些只包含 two 的情况。

这是我的尝试:

for x in list1:
    uid = x['id']
    if uid == x['id'] and x['custom'] == 'two':
        print(x)

我期望的输出应该是 id 5 和 2。

但现在的输出却显示了 1、2、3 和 5。

4 个回答

2

也许我们可以先找出那些值为 one 的ID,然后再检查这些ID中有没有值为 two 的。

from collections import defaultdict

list1 = [
    {'id': 1, 'custom': 'one'},
    {'id': 2, 'custom': 'two'},
    {'id': 3, 'custom': 'one'},
    {'id': 1, 'custom': 'two'},
    {'id': 3, 'custom': 'two'},
    {'id': 4, 'custom': 'one'},
    {'id': 5, 'custom': 'two'},
]

ids_with_one = defaultdict(bool)
for item in list1:
    if item['custom'] == 'one':
        ids_with_one[item['id']] = True

for item in list1:
    if item['custom'] == 'two' and not ids_with_one[item['id']]:
        print(item['id'])

示例链接: https://www.online-python.com/nSLCTrb8kj

2

一种方法是使用一个叫做 defaultdict 的工具,把数据整理在一起,然后找出那些只有 two 这个值的条目。

from collections import defaultdict
dd = defaultdict(list)
for entry in list1:
    dd[entry['id']].append(entry['custom'])
print([key for key in dd if dd[key] == ['two']])

输出结果

[2, 5]
1
list1 = [
    {'id': 1, 'custom': 'one'},
    {'id': 2, 'custom': 'two'},
    {'id': 3, 'custom': 'one'},
    {'id': 1, 'custom': 'two'},
    {'id': 3, 'custom': 'two'},
    {'id': 4, 'custom': 'one'},
    {'id': 5, 'custom': 'two'},
]

print({d['id'] for d in list1}
    - {d['id'] for d in list1 if d['custom'] != 'two'})

这是一个链接,你可以点击它来在线尝试一些代码。它会带你到一个网站,在那里你可以运行代码,看看它是怎么工作的。这个链接的内容是为了帮助你更好地理解编程。只需点击一下,就能开始你的编程体验!

撰写回答