【问题标题】:Python merging two list into dictionaries, add valuesPython将两个列表合并到字典中,添加值
【发布时间】:2022-07-06 00:00:26
【问题描述】:

鉴于以下两个列表,一个包含字符串,一个包含整数,如何在添加重复键的值时将这两个列表合并到字典中?

字符串列表 = [“EL1”、“EL2”、“EL1”、“EL3”、“El4”]

整数列表 = [1, 2, 12, 4, 5]

所以在最终字典中,我希望 EL1 为 13,因为它还包含 1 和 12。

resultdictionary = {}
for key in appfinal:
    for value in amountfinal:
        resultdictionary[key] = value
        amountfinal.remove(value)
        break

在这种情况下,结果字典会删除所有重复的键,但会采用与这些键匹配的最后一个值。所以,EL1 是 12。

有什么想法吗?谢谢。

【问题讨论】:

  • 测试字典是否已经包含键。如果是,则添加该值而不是替换它。
  • 或使用defaultdict(int)
  • 不要使用嵌套循环。使用zip() 并行遍历两个列表。

标签: python python-3.x list dictionary


【解决方案1】:

一种可能的解决方案是将dict.get 与默认值0 一起使用。例如:

stringlist = ["EL1", "EL2", "EL1", "EL3", "El4"]
integerlist = [1, 2, 12, 4, 5]

resultdictionary = {}
for s, i in zip(stringlist, integerlist):
    resultdictionary[s] = resultdictionary.get(s, 0) + i

print(resultdictionary)

打印:

{'EL1': 13, 'EL2': 2, 'EL3': 4, 'El4': 5}

【讨论】:

    【解决方案2】:

    使用defaultdict() 创建一个字典,根据需要自动创建键。

    使用zip() 将两个列表一起循环。

    from collections import defaultdict
    
    resultdictionary = defaultdict(int)
    for key, val in zip(stringlist, integerlist):
        resultdictionary[key] += val
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2020-08-05
      • 2013-11-02
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多