Python-如何在字典中获取具有相同值的键/

时间:2020-08-05 07:57:47

标签: python dictionary

我有一个字典:

{'Key_1': ['Value_1'], 'Key_2': ['Value_1', 'Value_2'], 'Key_3': ['Value_2'], 'Key_4': ['Value_3']}

我想获得具有相同值的键,例如,输出如下:

Key_1 and Key_2 have same Value_1
Key_2 and Key_3 have same Value_2

我试图这样做以获得共同的价值观:

list_1 = []
output = []
for value in dictionary.values():
    for x in value:
         if x in list_1:
            if not x in output:
                output.append(x)
         else:
             list_1.append(x)

通过此操作,我可以获得公用值,但没有相应的键。

提前谢谢!

1 个答案:

答案 0 :(得分:3)

d = {'Key_1': ['Value_1'], 'Key_2': ['Value_1', 'Value_2'], 'Key_3': ['Value_2'], 'Key_4': ['Value_3']}

out = {}
for k, v in d.items():
    for vv in v:
        out.setdefault(vv, []).append(k)

for k, v in out.items():
    if len(v) > 1:
        print('{} have same {}'.format(' and '.join(v), k))

打印:

Key_1 and Key_2 have same Value_1
Key_2 and Key_3 have same Value_2