将项添加到Python字典

Ste*_*ton 1 python dictionary add

我可能已经理解了这个错误,但是看看O'Reilly在"学习Python"中找到的例子我尝试做以下事情:

>>> d={}
>>> d['h']='GG'
>>> d['f']='JJ'
>>> d['h']='PP'
>>> print d
{'h': 'PP', 'f': 'JJ'}
Run Code Online (Sandbox Code Playgroud)

现在,而不是"关键" 'h'有两个项目'GG''PP'它只有最后一个条目,最后一个更换的第一个.我想要同一把钥匙.

>>> d['h']+='RR'
>>> print d
{'h': 'PPRR', 'f': 'JJ'}
Run Code Online (Sandbox Code Playgroud)

再次这不起作用,我想要的不是串联字符串,而是逗号分隔的entires.

我很困惑,为什么这不起作用.

Mar*_*ers 6

您的用例可以通过collections.defaultdict()类型很好地处理:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['h'].append('GG')
>>> d['f'].append('JJ')
>>> d['h'].append('PP')
>>> d
defaultdict(<type 'list'>, {'h': ['GG', 'PP'], 'f': ['JJ']})
Run Code Online (Sandbox Code Playgroud)

一个普通的字典映射一个一个值,如果你想要的值是一个列表,那么你应该让一个列表,并追加到列表中,而不是.

你不具备使用一个defaultdict()对象,你总是可以让你的价值观明确列出:

>>> d = {}
>>> d['h'] = ['GG']
>>> d['f'] = ['JJ']
>>> d['h'].append('PP')
>>> print d
{'h': ['GG', 'PP'], 'f': ['JJ']}
Run Code Online (Sandbox Code Playgroud)

但现在你需要明确地创建列表.然后可以通过使用dict.setdefault()以下方法再次规避后一个问题:

>>> d = {}
>>> d.setdefault('h', []).append('GG')
>>> d.setdefault('f', []).append('JJ')
>>> d.setdefault('h', []).append('PP')
Run Code Online (Sandbox Code Playgroud)

这只是一种使用defaultdict()对象可以直接提供的更冗长的方式.