python - 基于共同值合并两个字典的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]
}
--> 结果允许从一个标识符映射到另一个。
解决方案
你可以使用类似的东西:
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
让我们分解它以供您理解。
- 要获得“主键”,我正在使用
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()))
返回字典中的第一个键。
- 要为每个字典值并行迭代,我正在使用
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]]
).
推荐阅读
- elasticsearch - 获取 ElasticSearch 嵌套字段中每个组的最新记录
- android - firebase phone auth sms 包含模板中不存在的额外字符
- android-studio - 应用因违反我们的恶意行为或用户数据政策以及包含安全漏洞的软件而被拒绝
- elasticsearch - 按时间过滤任何日期
- java - Jenkins-Rest - 连接到远程詹金斯客户端
- django - 如何让 Django 自己发送请求
- c++ - 如何使用 C++ 中的友元函数初始化类的私有成员?
- ios - 在 Swift 5.3 中渲染 GIF
- logstash - logstash 因“NoMethodError:nil:NilClass 的未定义方法 `multi_filter'”而崩溃
- pine-script - Pine Script:如何找到两个柱索引之间的最高柱?