python字典中的多个键可以吗? [英] multiple keys in python dictionary, is possible?

查看:962
本文介绍了python字典中的多个键可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中构建一个字典,其中不同的键指向相同的元素。我有这个字典:

I'd like to build a dictionary in python in which different keys refer to the same element. I have this dictionary:

persons = {"George":'G.MacDonald', "Luke":'G.MacDonald', "Larry":'G.MacDonald'} 

键全部指向一个相同的字符串,字符串在程序中有不同的内存位置,我想制作一个字典,其中所有这些键指向相同的元素,是可能吗?

the key refer all to an identical string but the strings have different memory location inside the program, I'd like to make a dictionary in which all these keys refer to the same element, is that possible?

推荐答案

您可以执行以下操作:

import itertools as it

unique_dict = {}
value_key=lambda x: x[1]
sorted_items = sorted(your_current_dict.items(), key=value_key)
for value, group in it.groupby(sorted_items, key=value_key):
    for key in group:
        unique_dict[key] = value

将您的字典转换为字典,其中任何类型(但可比较)的相等值是唯一的。如果你的值不可比较(但是可以是hash),你可以使用一个临时的 dict

This transforms your dictionary into a dictionary where equal values of any kind(but comparable) are unique. If your values are not comparable(but are hashable) you could use a temporary dict:

from collections import defaultdict
unique_dict = {}
tmp_dict = defaultdict(list)

for key, value in your_current_dict.items():
    tmp_dict[value].append(key)

for value, keys in tmp_dict.items():
    unique_dict.update(zip(keys, [value] * len(keys)))

这篇关于python字典中的多个键可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆