[英]how to append a new value to the existing dict key without overwrite
The title describes the problem, this is what i tried and this is not giving me expected resoult.. where is the problem? 标题描述了问题,这是我尝试过的,并且没有给我预期的结果..问题出在哪里?
for name in file:
if name in list:
if dict.has_key(param):
dict[param] = [dict[param],name]
else:
dict[param] = name
expecting output: 预期的输出:
dict = {
'param1': ['name11', 'name12', 'name13'],
'param2': ['name21', 'name22', 'name23'],
.
.
.
}
You need to append these names to a list. 您需要将这些名称附加到列表中。 The following is a naive example and might break. 以下是一个幼稚的示例,可能会中断。
for name in file:
if name in list:
if dict.has_key(param):
dict[param].append(name)
else:
dict[param] = [name]
Or if you want to be a little cleaner, you can use collections.defaultdict
. 或者,如果您想更清洁一点,可以使用collections.defaultdict
。 This is the pythonic way if you ask me. 如果您问我,这就是Python的方法。
d = collections.defaultdict(list)
for name in file:
if name in lst: # previously overwrote list()
d[param].append(name)
Please do not overwrite the builtin dict()
or list()
function with your own variable. 请不要用您自己的变量覆盖内置的dict()
或list()
函数。
You are looking for a multi map, ie a map or dictionary which does not have a key -> value relation but a key -> many values, see: 您正在寻找多地图,即没有键->值关系但键->许多值的地图或词典,请参见:
See Is there a 'multimap' implementation in Python? 请参阅Python中是否有“多图”实现?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.