向同一个键添加更多值

Mon*_*ois 0 python dictionary key-value python-2.7

我想知道是否有一个命令可以做到这一点:

>>>A=dict()
>>>A[1]=3
>>>A
   {1:3}
>>>A[1].add(5)        #This is the command that I don't know if exists.
>>>A
   {1:(3,5)}
Run Code Online (Sandbox Code Playgroud)

我的意思是,在不退出旧值的情况下向同一个键添加另一个值.有可能这样做吗?

iCo*_*dez 5

您可以将字典值转换为列表:

>>> A = dict()
>>> A[1] = [3]
>>> A
{1: [3]}
>>> A[1].append(5)  # Add a new item to the list
>>> A
{1: [3, 5]}
>>>
Run Code Online (Sandbox Code Playgroud)

您可能也感兴趣dict.setdefault,其功能类似于collections.defaultdict但无需导入:

>>> A = dict()
>>> A.setdefault(1, []).append(3)
>>> A
{1: [3]}
>>> A.setdefault(1, []).append(5)
>>> A
{1: [3, 5]}
>>>
Run Code Online (Sandbox Code Playgroud)