使用Python

时间:2019-07-10 13:42:20

标签: python loops dictionary

在给定列表中:

unmatched_items_array = [{'c': 45}, {'c': 35}, {'d': 5}, {'a': 3.2}, {'a': 3}]

找到所有“键”对并打印,如果找不到给定字典的对,则打印该字典。

到目前为止,我设法编写了一些作品,但是即使已经测试过,它仍继续测试列表中的某些项目。不确定如何解决。

for i in range(len(unmatched_items_array)):
        for j in range(i + 1, len(unmatched_items_array)):
            #  when keys are the same print matching dictionary pairs
            if unmatched_items_array[i].keys() == unmatched_items_array[j].keys():
                print(unmatched_items_array[i], unmatched_items_array[j])
                break
        #  when no matching pairs print currently processed dictionary
        print(unmatched_items_array[i])

输出:

{'c': 45} {'c': 35}
{'c': 45}
{'c': 35}
{'d': 5}
{'a': 3.2} {'a': 3}
{'a': 3.2}
{'a': 3}

输出应为:

{'c': 45} {'c': 35}
{'d': 5}
{'a': 3.2} {'a': 3}

我在这里做什么错了?

2 个答案:

答案 0 :(得分:2)

使用collections.defaultdict

例如:

from collections import defaultdict

unmatched_items_array = [{'c': 45}, {'c': 35}, {'d': 5}, {'a': 3.2}, {'a': 3}]
result = defaultdict(list)

for i in unmatched_items_array:
    key, _ = i.items()[0]
    result[key].append(i)          #Group by key. 

for _, v in result.items():        #print Result. 
    print(v)

输出:

[{'a': 3.2}, {'a': 3}]
[{'c': 45}, {'c': 35}]
[{'d': 5}]

答案 1 :(得分:1)

使用itertools.groupby

from itertools import groupby

unmatched_items_array = [{'d': 5}, {'c': 35}, {'a': 3}, {'a': 3.2}, {'c': 45}]

for v, g in groupby(sorted(unmatched_items_array, key=lambda k: tuple(k.keys())), lambda k: tuple(k.keys())):
    print([*g])

打印:

[{'a': 3}, {'a': 3.2}]
[{'c': 35}, {'c': 45}]
[{'d': 5}]

编辑:如果列表中的项目已经按键排序,则可以跳过sorted()调用:

for v, g in groupby(unmatched_items_array, lambda k: tuple(k.keys()) ):
    print([*g])