首页 > 解决方案 > 基于共同值合并两个字典的Python方式?

问题描述

给定两个字典:

a = {
    'key_one': 'abc',
    'key_two': 'def',
    'key_three': 'ghi'
}

b = {
    'key_alpha': 'kappa',
    'key_beta': 'def',
    'key_gamma': 'epsilon'
}

有没有一种优雅的、pythonic 的方式通过它们的共同价值来合并这两个字典'def'

结果应该是:

res = {
    'def': ['abc', 'kappa']
}

即我实际上正在寻找'abc'to的映射'kappa'


编辑:改进的例子:

a = {
    'key_one': 4,
    'key_two': 'def',
    'key_three': 'ghi'
}

b = {
    'key_alpha': 19,
    'key_beta': 'def',
    'key_gamma': 'epsilon'
}

结果:

res = {
    'def': [4, 19]
}

--> 结果允许从一个标识符映射到另一个。

标签: python

解决方案


你可以使用类似的东西:

def merge(d1, d2):
    result = {}
    
    # Get the primary keys of each dictionary
    # The primary key will be the first element
    # from the set of keys of each dict
    pk1 = next(iter(d1.keys()))
    pk2 = next(iter(d2.keys()))
    
    # Iterate in parallel for each value
    for v1, v2 in zip(d1.values(), d2.values()):
        if v1 == v2:
            result[v1] = [d1[pk1], d2[pk2]]
            
    return result

让我们分解它以供您理解。

  1. 要获得“主键”,我正在使用next(iter(d.keys()))
a = {'key_one': 'abc', 'key_two': 'def', 'key_three': 'ghi'}

print(a.keys())
# Outputs dict_keys(['key_one', 'key_two', 'key_three'])

print(next(iter(a.keys())))
# Outputs key_one

所以next(iter(d.keys()))返回字典中的第一个键。

  1. 要为每个字典值并行迭代,我正在使用zip(d1.values(), d2.values())
a = {'key_one': 'abc', 'key_two': 'def', 'key_three': 'ghi'}
b = {'key_alpha': 'kappa', 'key_beta': 'def', 'key_gamma': 'epsilon'}

print(a.values())
# Outputs dict_values(['abc', 'def', 'ghi'])

print(b.values())
# Outputs dict_values(['kappa', 'def', 'epsilon'])

for va, vb in zip(a.values(), b.values()):
    print(va, vb)
    # Outputs
    #   abc kappa
    #   def def
    #   ghi epsilon

Finally, I just compare if both values are equal (note above that, in the second iteration, both values are equal since "def" == "def"). If they are, I add this value (v1) as a key to a dictionary (result) and assign it to a list ([...]) containing the "primary keys" ([...[pk1], ...[pk2]]) of each input dictionary ([d1[pk1], d2[pk2]]).


推荐阅读