2016-07-13 23 views
3

辞書を辞書のキーとして使用する方法はありますか?現在、私はこれに対して2つのリストを使用していますが、辞書を使用するのが良いでしょう。ここで私は現在やっているものです:辞書を辞書のキーとして使用する

ここ
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" 

をしかし、これは動作しませんし、私はこの周りにどのような方法があるかどうかわかりません。

+1

あなたは辞書のキーとして可変オブジェクトを使用するので、ありませんすることはできません。それは不可能。 – zondo

+0

それを行うことはできませんが、[名前付きタプル](http://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python)が良い代替手段になる可能性があります。 – JGreenwell

答えて

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 
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] 
3

役立ちますね。辞書は変更可能であるため、辞書キーとして使用することはできません。 (つまり、文字列、タプル、等)を使用すると、辞書の項目も不変であることを行っていることを保証することができる場合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)のペアをソートします。次に、このタプルを辞書のキーとして使用します。

+0

['OrderedDict'](https://docs.python.org/3/library/collections.html#collections.OrderedDict)を参照してください。そうすれば、OPは毎回辞書をソートすることを覚えておく必要はありません。 –

関連する問題