[英]Using a dictionary as a key in a 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"
但這不起作用,我不確定是否有任何解決方法。
字典鍵必須是不可變的。 字典是可變的,因此不能用作字典密鑰。 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)
對進行排序以確保元組內的一致排序。 然后我們使用這個元組作為你字典的關鍵。
正如其他答案所指出的那樣,你不能使用字典作為鍵,因為鍵需要是不可變的。 你可以做的是將字典frozenset
為(key, value)
元組的frozenset
集,你可以將它們用作鍵。 這樣您就不必擔心排序了,它也會更有效:
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
我想這會對你有所幫助
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.