简体   繁体   English

Python将两个列表合并到字典中,添加值

[英]Python merging two list into dictionaries, add values

Given the two following lists, one containing strings, one integers, how can I merge these two lists into a dictionary while ADDING the values for duplicate keys?给定以下两个列表,一个包含字符串,一个包含整数,如何在添加重复键的值时将这两个列表合并到字典中?

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

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

So in the final dictionary I'd like EL1 to be 13, because it also contains 1 and 12.所以在最终的字典中,我希望 EL1 是 13,因为它还包含 1 和 12。

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

In this case, result dictionary removes any duplicate keys, but takes the last value that matches those keys.在这种情况下,结果字典会删除任何重复的键,但会采用与这些键匹配的最后一个值。 So, EL1 would be 12.因此,EL1 将是 12。

Any ideas?有任何想法吗? Thank you.谢谢你。

Use defaultdict() to create a dictionary that automatically creates keys as needed.使用defaultdict()创建一个字典,根据需要自动创建键。

Use zip() to loop over the two lists together.使用zip()将两个列表一起循环。

from collections import defaultdict

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

One possible solution is to use dict.get with defaultvalue 0 .一种可能的解决方案是将dict.get与 defaultvalue 0一起使用。 For example:例如:

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)

Prints:印刷:

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

Zany solution for funsies:有趣的滑稽解决方案:

stringlist = ["EL1", "EL2", "EL1", "EL3", "El4"]

integerlist = [1, 2, 12, 4, 5]

result = {}
result.update((k, result.get(k, 0) + v) for k, v in zip(stringlist, integerlist))
print(result)

Try it online! 在线尝试!

It's almost a one-liner, but still needs result to be defined as an empty dict first , so it can use a genexpr that lazily checks the value summed so far as it goes.几乎是单行的,但仍然需要先将result定义为空dict ,因此它可以使用一个可以懒惰地检查总和的值的genexpr 。

I don't actually recommend this.我实际上不推荐这个。 For one thing, I'm not sure the language spec strictly requires that dict.update evaluate the argument provided lazily;一方面,我不确定语言规范是否严格要求dict.update评估惰性提供的参数; if it tried to optimize by eagerly converting it to a dict first, then merging, this would fail.如果它试图通过首先将其转换为dict然后合并来进行优化,这将失败。 For another, it's easily broken (a maintainer might blindly convert the genexpr to a dictcomp or listcomp and now it's eager and broken).另一方面,它很容易被破坏(维护者可能会盲目地将genexpr 转换为dictcomp 或listcomp,现在它急切而被破坏)。 And the genexpr, while it technically has no side-effects itself, is relying on the side-effects of it being consumed by result.update , which is a distinctly non-functional design at odds with the functional style of genexprs.而且,虽然从技术上讲,genexpr 本身没有副作用,但它依赖于它被result.update消耗的副作用,这是一种明显的非功能设计,与 genexprs 的功能风格不一致。

The quickest way w/o imports would be like this:没有进口的最快方式是这样的:

stringlist = ["EL1", "EL2", "EL1", "EL3", "El4"]

integerlist = [1, 2, 12, 4, 5]

#Convert two Lists into Dictionary using zip()
mergeLists = dict(zip(stringlist, integerlist))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM