简体   繁体   English

如何在不覆盖的情况下将新值附加到现有的dict键

[英]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.

相关问题 如何基于Python中的匹配键将键值对添加到另一个字典列表中的现有字典列表中 - How to append key value pair to an existing list of dict from another list of dict based on matching Key in Python Python:如何在没有“键”的情况下追加到字典? - Python: How to append to dict without “key”? 如何在Python dict的值前附加键? - How to append a key before a value in Python dict? 如何在不创建新键的情况下访问 for 循环中的现有 dict 键? - How to access existing dict key inside a for loop without creating a new key? 如何将新键添加到现有字典并将前一个键作为值附加到 for 循环中创建的新键:python - How to add a new key to an existing dictionary and append previous key as value to the new key created in a for loop : python 在 pymongo 中:我如何在现有数组中 append 新字典 - In pymongo: How can I append new dict in an existing array 为键添加一个值而不是覆盖-Python中的Dict - Add a value to key instead of overwrite - Dict in python 如何将值附加到尚不存在的键? - How to append a value to a not yet existing key? 如何从dict返回某些键,值并打印新的dict - how to return certain key, value from dict and print new dict 如何将正则表达式的两个列表附加为字典键值对 - How to append two lists of a regular expression as a dict key value pairs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM