【问题标题】:How do I merge multiple dictionaries values having same key in python?如何在python中合并具有相同键的多个字典值?
【发布时间】:2018-08-02 06:58:02
【问题描述】:

我有 n 个这样的字典:

dict_1 = {1: {'Name': 'xyz', 'Title': 'Engineer'}, 2: {'Name': 'abc', 
         'Title': 'Software'}}
dict_2 = {1: {'Education': 'abc'}, 2: {'Education': 'xyz'}}
dict_3 = {1: {'Experience': 2}, 2:{'Experience': 3}}
.
.
.
dict_n

我只想像这样根据主键组合所有这些:

final_dict = {1: {'Name': 'xyz', 'Title': 'Engineer', 'Education': 
            'abc', 'Experience': 2}, 
             2: {'Name': 'abc', 'Title': 'Software', 'Education': 
            'xyz', 'Experience': 3}}

谁能帮我实现这个目标?

【问题讨论】:

  • 我们帮助您解决代码中的错误。没有代码,没有错误需要我们解决。
  • 你尝试了什么?
  • 标记python-3.x 和 python-2.7 无助于识别您询问的Python 版本。
  • 我正在寻找解决方案,我需要代码 sn-p 来实现 final_dict

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

根据您的问题,我认为您有 n 个字典。因此,列出您的 dicts 并组合具有相同键的所有值。
但这本身并不能给出确切的答案。它们是字典列表。所以我做的第二件事就是把所有这些小字典变成一个字典。

你可以在这里查看我的代码:

d1 = {1: {'Name': 'xyz', 'Title': 'Engineer'}, 2: {'Name': 'abc', 
  'Title': 'Software'}}
d2 = {1: {'Education': 'abc'}, 2: {'Education': 'xyz'}}
d3 = {1: {'Experience': 2}, 2:{'Experience': 3}}

ds = [d1, d2, d3] # list of your dicts you can change it to dict_

big_dict = {}
for k in ds[0]:
   big_dict[k] = [d[k] for d in ds]

for k in big_dict.keys():
    result = {}
    for d in big_dict[k]:
        result.update(d)
    big_dict[k] = result
print(big_dict)

它给出这样的 O/P:

{
1: {'Education': 'abc', 'Title': 'Engineer', 'Name': 'xyz', 
   'Experience': 2}, 
2: {'Education': 'xyz', 'Title': 'Software', 'Name': 'abc', 
   'Experience': 3}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多