gpt4 book ai didi

python - 如何按值过滤字典?

转载 作者:太空狗 更新时间:2023-10-30 00:25:45 24 4
gpt4 key购买 nike

这里是新手问题,所以请耐心等待。

假设我有一本如下所示的字典:

a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}

我希望将所有彼此相等的值移动到另一个字典中。

matched = {"2323232838": ("first/dir", "hello.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt")}

剩下的不匹配项应该是这样的:

remainder = {"2323221383": ("second/dir", "foo.txt"),
"324234324": ("third/dir", "dog.txt")}

在此先感谢,如果您提供示例,请尽可能多地发表评论。

最佳答案

下面的代码将产生两个变量,matchesremaindersmatches 是一个字典数组,其中来自原始字典的匹配项目将有一个对应的元素。 remainder 将包含一个包含所有不匹配项的字典。

请注意,在您的示例中,只有一组匹配值:('first/dir', 'hello.txt')。如果有多个集合,则每个集合在 matches 中都有对应的条目。

import itertools

# Original dict
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}

# Convert dict to sorted list of items
a = sorted(a.items(), key=lambda x:x[1])

# Group by value of tuple
groups = itertools.groupby(a, key=lambda x:x[1])

# Pull out matching groups of items, and combine items
# with no matches back into a single dictionary
remainder = []
matched = []

for key, group in groups:
group = list(group)
if len(group) == 1:
remainder.append( group[0] )
else:
matched.append( dict(group) )
else:
remainder = dict(remainder)

输出:

>>> matched
[
{
'3434221': ('first/dir', 'hello.txt'),
'2323232838': ('first/dir', 'hello.txt'),
'32232334': ('first/dir', 'hello.txt')
}
]

>>> remainder
{
'2323221383': ('second/dir', 'foo.txt'),
'324234324': ('third/dir', 'dog.txt')
}

作为新手,您可能会在上面的代码中了解到一些不熟悉的概念。以下是一些链接:

关于python - 如何按值过滤字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1241029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com