合并字典以保留相同值以及不同值。

huangapple go评论67阅读模式
英文:

combining dictionaries to keep same values along with different values

问题

You can combine the dictionaries in Python by iterating through them and checking for unequal values. Here's the code to achieve the expected output:

x = {'a': 1, 'b': 2, 'c': 3, 'd': 2}
y = {'a': 1, 'b': 3, 'c': 4, 'd': 2}
z = {}

for key in x:
    if x[key] != y[key]:
        z[key] = f"{x[key]} to {y[key]}"
    else:
        z[key] = x[key]

print(z)

This code will give you the desired output:

{'a': 1, 'b': '2 to 3', 'c': '3 to 4', 'd': 2}
英文:

I have two dictionaries with the values.

x = {'a': 1, 'b': 2, 'c': 3, 'd':2}
y = {'a': 1, 'b': 3, 'c': 4, 'd':2}

How could I combine the values in python where these are not equal and if equal keep the same?

Expected output:

z = {'a': 1, 'b': 2 to 3, 'c': 3 to 4, 'd':2}

答案1

得分: 0

Here are the translations of the code sections you provided:

  1. 假设两个字典中的键相同,使用字典推导式和条件语句:
z = {k: v - y[k] if v != y[k] else v for k, v in x.items()}

输出: {'a': 1, 'b': -1, 'c': -1, 'd': 2}

  1. 对于元组:
z = {k: (v, y[k]) if v!=y[k] else v for k, v in x.items()}

输出: {'a': 1, 'b': (2, 3), 'c': (3, 4), 'd': 2}

  1. 对于字符串:
z = {k: f'{v} to {y[k]}' if v!=y[k] else v for k, v in x.items()}

输出: {'a': 1, 'b': '2 to 3', 'c': '3 to 4', 'd': 2}

  1. 用于任意数量的字典的通用方法:
dicts = [x, y]

out = {}
for d in dicts:
    for k, v in d.items():
        out.setdefault(k, set()).add(v)

out = {k: ', '.join(map(str, v)) for k, v in out.items()}

输出: {'a': '1', 'b': '2, 3', 'c': '3, 4', 'd': '2'}

英文:

Assuming the keys are identical in the two dictionaries, use a dictionary comprehension with a conditional:

z = {k: v - y[k] if v != y[k] else v for k, v in x.items()}

Output: {'a': 1, 'b': -1, 'c': -1, 'd': 2}

edited answer

For a tuple:

z = {k: (v, y[k]) if v!=y[k] else v for k, v in x.items()}

Output: {'a': 1, 'b': (2, 3), 'c': (3, 4), 'd': 2}

And a string:

z = {k: f'{v} to {y[k]}' if v!=y[k] else v for k, v in x.items()}

Output: {'a': 1, 'b': '2 to 3', 'c': '3 to 4', 'd': 2}

generic approach for an arbitrary number of dictionaries

dicts = [x, y]

out = {}
for d in dicts:
    for k, v in d.items():
        out.setdefault(k, set()).add(v)

out = {k: ', '.join(map(str, v)) for k, v in out.items()}

Output: {'a': '1', 'b': '2, 3', 'c': '3, 4', 'd': '2'}

huangapple
  • 本文由 发表于 2023年5月25日 17:49:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定