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