【问题标题】:How to merge two dictionaries that are with a dictionary in python?如何在python中合并两个字典?
【发布时间】:2017-04-18 06:50:18
【问题描述】:

以下是来自类似输入的巨大文件的示例输入。

{
    "V-Su7890": [
        [
            {
                "url": "www.talent.com",
                "tid": "V-Su7890",
                "id": "58ff787ffbad487b2c",
                "company_name": "Talent Ltd"
            }
        ],
        [
            {
                "socials": ["facebook", "linkedin", "twitter"],
                "title": "title of the pag",
                "contact": ["+9563802140"],
                "email": "email_id1"
            },
            {
                "socials": ["facebook", "twitter", "linkedin"],
                "title": "next title of the page",
                "contact": ["+919765983442"],
                "email": "email_id2"
            }
        ]
    ]
}

我必须将当前字典的第二个列表的所有子字典合并到一个没有重复值的字典中,然后将字典作为值存储到键“V-Su7890”中。

想要的输出是:

{
    "V-Su7890": [
        [
            {
                "url": "www.talent.com",
                "tid": "V-Su7890",
                "id": "58ff787ffbad487b2c",
                "company_name": "Talent Ltd"
            }
        ],
        [
            {
                "socials": ["facebook", "linkedin", "twitter"],
                "title": ["title of the pag", "next title of the page"],
                "contact": ["+9563802140", "+919765983442"],
                "email": ["email_id","email_id2"]
            }
        ]
    ]
}

请帮助我理解并解决这个问题。

【问题讨论】:

  • 到目前为止您尝试了哪些方法,遇到了哪些问题?

标签: python dictionary merge


【解决方案1】:

您可以使用setdefault() 插入值为默认值的键(这里您可以使用空列表),如果新项目不存在,则使用extend 列表。

for k,v in a.items():
    tmp={}
    for i in v[1]:
        for k1,v2 in i.items():
            if isinstance(v2,list):
                tmp.setdefault(k1,[]).extend(i for i in v2 if i not in tmp[k1])
            else:
                tmp.setdefault(k1,[]).append(v2)
    a[k]=[v[0],[tmp]]
print(a)

结果:

{
  'V-Su7890': [
    ...
    [
      {
        'contact': ['+9563802140','+919765983442'],
        'socials': ['facebook','linkedin','twitter'],
        'email': ['email_id1','email_id2'],
        'title': ['title of the pag','next title of the page']
      }
    ]
  ]
}

【讨论】:

  • 谢谢,但是,这也将下一条记录合并到上一个字典中。例如,{ "V-Su7890":[.......................],''V-SZ86385ZM':[............ ..]} 并且“电子邮件”中的值包含重复项。
  • @Niveram 我编辑了我的答案,将tmp={} 放入 for 循环中,它不会合并下一条记录。
  • 太好了.. 谢谢麦格雷迪。
  • 嗨 McGrady,我的输入是 {u'V-WW62364WT':[[{....... .], u'V-YS87486IT': its values,u'V-SZ86385ZM': its values} 是否有可能在键处拆分,因此上述代码可以完美运行。
【解决方案2】:

假设您将完整的 dict 存储在变量 V 中。我们将 socialstitle 等的值存储在一个集合中以避免重复值。稍后,我们会将集合转换为列表。这是解决方案:

V = k["V-Su7890"][1]
new_dict = {}

for v in V:
    for key, value in v.iteritems():
        if not new_dict.get(key, None):
            new_dict[key] = set()

        if isinstance(value, list):
            for val in value:
                new_dict[key].add(val)
        else:
            new_dict[key].add(value)

# Converting the sets to list
for key, value in new_dict.iteritems():
    new_dict[key] = list(value)

k["V-Su7890"][1] = [new_dict]

【讨论】:

  • 抱歉,我有疑问。什么是 V = k["V-Su7890"][1] ?您提到“将完整的字典存储在变量 V 中”,但该文件仅包含我在上面采样的字典列表
  • 您已将原始字典列表括在大括号内,花括号本身就是一个字典。 {“V-Su7890”:[...]}
猜你喜欢
  • 2022-11-15
  • 2022-12-26
  • 2022-12-18
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 2019-05-16
相关资源
最近更新 更多