简体   繁体   English

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

[英]Python - How to get keys with same values in a dictionary/

I have a dict:我有一个字典:

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

I would like to get the keys with the same values eg, an output like:我想获得具有相同值的键,例如 output ,例如:

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

I tried this to get the common values:我试过这个来获得共同的价值观:

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)

With this I get the common values but not the corresponding keys.有了这个,我得到了共同的值,但没有得到相应的键。

Thank you in advance!先感谢您!

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))

Prints:印刷:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM