我有一个字典:{'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_1Key_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 回答
翻过高山走不出你
TA贡献1875条经验 获得超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
添加回答
举报
0/150
提交
取消