如何创建一个字典,其中包含一个值的多个键?

我有一个关于我想做的词典的问题。我的目标是对单个值使用多个键,如下所示:

dictionary = {('a', 'b'): 1, ('c', 'd'): 2}
assert dictionary['a'] == 1
assert dictionary['b'] == 1

有什么想法吗?

196022 次浏览

我想你的意思是:

class Value:
def __init__(self, v=None):
self.v = v


v1 = Value(1)
v2 = Value(2)


d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1


d['b'].v == 2 # True
  • Python 的字符串和数字是 永恒不变对象,
  • 因此,如果您希望 d['a']d['b']指向 同样的价值,在它变化时“更新”,那么让该值引用 易变的对象(类似上面的用户定义类,或者 dictlistset)。
  • Then, when you modify the object at d['a'], d['b'] changes at same time because they both point to same object.

Your example creates multiple key: value pairs if using fromkeys. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.

>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True

If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-key-that-will-return-the-same-value.

However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:

alias = {
'a': 'id1',
'b': 'id1',
'c': 'id2',
'd': 'id2'
}


dictionary = {
'id1': 1,
'id2': 2
}


dictionary[alias['a']]

如果你需要添加到字典中,你可以编写这样一个函数来同时使用这两个字典:

def add(key, id, value=None)
if id in dictionary:
if key in alias:
# Do nothing
pass
else:
alias[key] = id
else:
dictionary[id] = value
alias[key] = id


add('e', 'id2')
add('f', 'id3', 3)

虽然这种方法很有效,但我认为最终如果您想要做类似的事情,那么编写您自己的数据结构可能是最好的方法,尽管它可以使用类似的结构。

很简单。首先,您必须了解 Python 解释器的设计。它不会为所有的变量分配内存基本上如果任何两个或更多的变量有相同的值它只是映射到该值。

让我们来看代码示例,

In [6]: a = 10


In [7]: id(a)
Out[7]: 10914656


In [8]: b = 10


In [9]: id(b)
Out[9]: 10914656


In [10]: c = 11


In [11]: id(c)
Out[11]: 10914688


In [12]: d = 21


In [13]: id(d)
Out[13]: 10915008


In [14]: e = 11


In [15]: id(e)
Out[15]: 10914688


In [16]: e = 21


In [17]: id(e)
Out[17]: 10915008


In [18]: e is d
Out[18]: True
In [19]: e = 30


In [20]: id(e)
Out[20]: 10915296

在上面的输出中,变量 a 和 b 共享相同的内存,当我创建一个新的变量 e 并存储一个已经存在于变量 c 中的值(11)时,c 和 d 有不同的内存,所以它映射到那个内存位置,当我将变量 e 中的值改为21时,它不会创建一个新的内存,这个值已经存在于变量 d 中,所以现在变量 d 和 e 共享相同的内存位置。最后,我将变量 e 中的值改为30,这个值不存储在任何其他变量中,因此它为 e 创建了一个新的内存。

所以任何具有相同值的变量都共享内存。

不适用于列表和字典对象

我们来谈谈你的问题。

当多个键具有相同的值时,则所有键共享相同的内存,因此您所期望的内容已经存在于 python 中。

你可以像这样简单地使用它

In [49]: dictionary = {
...:     'k1':1,
...:     'k2':1,
...:     'k3':2,
...:     'k4':2}
...:
...:


In [50]: id(dictionary['k1'])
Out[50]: 10914368


In [51]: id(dictionary['k2'])
Out[51]: 10914368


In [52]: id(dictionary['k3'])
Out[52]: 10914400


In [53]: id(dictionary['k4'])
Out[53]: 10914400

从上面的输出,键 k1和 k2映射到相同的地址,这意味着值1存储在内存中只有一次,这是多键单值字典这是你想要的东西。校对: P

有多把钥匙

#!/usr/bin/env python3


def get_keys(s):
# Lower the user's entry to easily manipulate data
s = s.lower()
    

# Create a list to simulate multiple keys
numbers = ['uno', 'one', 'um', 'eins', 'ein']
    

# Lambda for input validation
validator = lambda key: key if key in numbers else 'no-key-found'  # return me x if x is found in the list numbers, contratiwise return me 'no-key-found'
    

dic = {
validator(s):'1',
'no-key-found':'Key does not exist'
}
    

    

return dic[validator(s)]




print(get_keys(input('Type in word: ')))

有动态钥匙

#!/usr/bin/env python3


import sys




def week_days():
# Assets
number_day = ['1', '2', '3', '4', '5', '6', '7']
    

# Introduction
print('Welcome to the Week Day Finder')
    

# User input
day = input('Please, enter the day you want to check: ').lower()
WEEK_COLOR = {'RED': '\u001b[31m', 'GREEN': '\u001b[32m'}
    

# Day validator
days = {
'1' if day in number_day else 'sunday': 'Weekend Day',
'2' if day in number_day else 'monday': 'Week Day',
'3' if day in number_day else 'tuesday': 'Week Day',
'4' if day in number_day else 'wednesday': 'Week Day',
'5' if day in number_day else 'thursday': 'Week Day',
'6' if day in number_day else 'friday': 'Week Day',
'7' if day in number_day else 'saturday': 'Weekend Day'
}
    

# Logical trial
try:
if days[day] == 'Week Day':
print(WEEK_COLOR['GREEN'], days[day])
            

else:
print(WEEK_COLOR['RED'], days[day])
            

except KeyError:
print('** Invalid Day **', file=sys.stderr)
        

        

def main():
week_days()
    

    

if __name__ == '__main__':
main()

享受使用解构分配的乐趣:

dictionary = {
**dict.fromkeys(['a', 'b'], 1),
**dict.fromkeys(['c', 'd'], 2),
}


assert dictionary['a'] == 1
assert dictionary['b'] == 1


# Elegant!!