python - 使用字典作为字典中的键

标签 python dictionary

有什么办法可以使用字典作为字典中的键。目前我为此使用了两个列表,但最好使用字典。这是我目前正在做的事情:

dicts = [{1:'a', 2:'b'}, {1:'b', 2:'a'}]
corresponding_name = ['normal', 'switcheroo']
if {1:'a', 2:'b'} in dicts:
    dict_loc = dicts.index({1:'a', 2:'b'})
    desired_name = corresponding_name[dict_loc]
    print desired_name

这是我想要的:

dict_dict = {{1:'a', 2:'b'}:'normal', {1:'b', 2:'a'}:'switcheroo'}
try: print dict_dict[{1:'a', 2:'b'}]
except: print "Doesn't exist"

但这行不通,我不确定是否有任何解决方法。

最佳答案

正如其他答案所指出的那样,您不能将字典用作键,因为键必须是不可变的。你可以做的是把字典变成 frozenset可以用作键的 (key, value) 元组。这样您就不必担心排序问题,而且效率也会更高:

dicts = [{1:'a', 2:'b'}, {1:'b', 2:'a'}]
corresponding_name = ['normal', 'switcheroo']

d = dict(zip((frozenset(x.iteritems()) for x in dicts), corresponding_name))

print d.get(frozenset({1:'a', 2:'b'}.iteritems()), "Doesn't exist")
print d.get(frozenset({'foo':'a', 2:'b'}.iteritems()), "Doesn't exist")

输出:

normal
Doesn't exist

关于python - 使用字典作为字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38341400/

相关文章:

python - Python 中高效的 CSV 阅读包?

python - 如何仅通过比较 pandas 中结果不匹配的列来创建数据框?

python - 值错误 : "too many values to unpack" when plotting with Sage

python - 如何从 Python 中的嵌套字典打印多个值

java - 如何将 Navigablemap 转换为 String[][]

c++ - 为什么要将 operator< 定义为非成员?

python - 从字符串中选择数据框行的条件

python - Python 错误的 Quantlib-SWIG 1.12.x,在 Windows 中缺少 Quantlib/quantlib_wrap.cpp

python - 选择哪种文件模式并循环创建列表

Python:使用字典从列表中删除重复项同时保留顺序