有没有办法使用字典作为字典中的键。目前我正在使用两个列表,但使用字典会很好。这是我目前正在做的事情:
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"
但这不起作用,我不确定是否有任何解决方法。
答案 0 :(得分:3)
A dictionary key has to be immutable. A dictionary is mutable, and hence can't be used as a dictionary key. https://docs.python.org/2/faq/design.html#why-must-dictionary-keys-be-immutable
如果你能保证字典项也是不可变的(即字符串,元组等),你可以这样做:
dict_dict = {}
dictionary_key = {1:'a', 2:'b'}
tuple_key = tuple(sorted(dictionary_key.items()))
dict_dict[tuple_key] = 'normal'
基本上,我们将每个字典转换为元组,对(key,value)
对进行排序以确保元组内的一致排序。然后我们使用这个元组作为你词典的关键。
答案 1 :(得分:3)
正如其他答案所指出的那样,你不能使用字典作为键,因为键需要是不可变的。你可以做的是将字典变成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
答案 2 :(得分:0)
我想这会对你有帮助
dicts = {
'normal' : "we could initialize here, but we wont",
'switcheroo' : None,
}
dicts['normal'] = {
1 : 'a',
2 : 'b',
}
dicts['switcheroo'] = {
1:'b',
2:'a'
}
if dicts.has_key('normal'):
if dicts['normal'].has_key(1):
print dicts['normal'][1]
print dicts['switcheroo'][2]