在字典中使用另一个字典作为键

3

有没有办法将字典作为另一个字典的键使用?目前我是用两个列表来实现,但使用字典会更好。以下是我当前的实现方式:

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
做不到,但你可能会发现命名元组是一个很好的替代方案。 - LinkBerest
3个回答

3
一个字典键必须是不可变的。 字典是可变的,因此不能用作字典键。 如果您可以保证字典项也将是不可变的(即字符串,元组等),则可以这样做:
dict_dict = {}
dictionary_key = {1:'a', 2:'b'}
tuple_key = tuple(sorted(dictionary_key.items()))
dict_dict[tuple_key] = 'normal'

基本上,我们将每个字典转换为元组,对 (key,value) 对进行排序,以确保元组内部的一致排序。然后,我们使用这个元组作为字典的键。

在这种情况下,使用OrderedDict可能会更好。这样一来,原帖的作者就不必每次都记得对字典进行排序了。 - Pierce Darragh

3

正如其他答案所指出的那样,您不能使用字典作为键,因为键需要是不可变的。但您可以将一个字典转换为由(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

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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接