首页 > 解决方案 > 如何在不覆盖数据的情况下加入/合并/更新 JSON 字典

问题描述

我有一个 JSON 字典列表,如下所示:

data = [{
    "title": "Bullitt",
    "release_year": "1968",
    "locations": "1153-57 Taylor Street",
    "fun_facts": "Embarcadero Freeway, which was featured in the film was demolished in 1989 because of structural damage from the 1989 Loma Prieta Earthquake)",
    "production_company": "Warner Brothers / Seven Arts\nSeven Arts",
    "distributor": "Warner Brothers",
    "director": "Peter Yates",
    "writer": "Alan R. Trustman",
    "actor_1": "Steve McQueen",
    "actor_2": "Jacqueline Bisset",
    "actor_3": "Robert Vaughn",
    "id": 498
},
{
    "title": "Bullitt",
    "release_year": "1968",
    "locations": "John Muir Drive (Lake Merced)",
    "production_company": "Warner Brothers / Seven Arts\nSeven Arts",
    "distributor": "Warner Brothers",
    "director": "Peter Yates",
    "writer": "Alan R. Trustman",
    "actor_1": "Steve McQueen",
    "actor_2": "Jacqueline Bisset",
    "actor_3": "Robert Vaughn",
    "id": 499
}]

如何在不覆盖数据的情况下组合这些字典?

所以,我想要得到的最终结果是:

data = {
    "title": "Bullitt",
    "release_year": "1968",
    "locations": ["1153-57 Taylor Street", "John Muir Drive (Lake Merced)"]
    "fun_facts": "Embarcadero Freeway, which was featured in the film was demolished in 1989 because of structural damage from the 1989 Loma Prieta Earthquake)",
    "production_company": "Warner Brothers / Seven Arts\nSeven Arts",
    "distributor": "Warner Brothers",
    "director": "Peter Yates",
    "writer": "Alan R. Trustman",
    "actor_1": "Steve McQueen",
    "actor_2": "Jacqueline Bisset",
    "actor_3": "Robert Vaughn",
    "id": 498, 499
}

我研究了合并 JSON 对象,但我遇到的只是覆盖数据。我不想覆盖任何东西。不太确定如何解决这个问题。

我是否必须为位置字段创建一个空列表并搜索整个数据集以查找相同的标题并获取它们的位置并将它们附加到空列表中,然后最后更新字典?或者当涉及到这样的事情时,有更好的方法/最佳实践吗?

标签: jsonpython-3.xmergeddictionaries

解决方案


这是一种使用简单迭代的方法。

前任:

result = {}
tolook = ('locations', 'id')
for d in data:
    if d['title'] not in result:
        result[d['title']] = {k: [v] if k in tolook else v for k, v in d.items()}
    else:
        for i in tolook:
            result[d['title']][i].append(d[i])

print(result) # Or result.values()

输出:

{'Bullitt': {'actor_1': 'Steve McQueen',
             'actor_2': 'Jacqueline Bisset',
             'actor_3': 'Robert Vaughn',
             'director': 'Peter Yates',
             'distributor': 'Warner Brothers',
             'fun_facts': 'Embarcadero Freeway, which was featured in the film '
                          'was demolished in 1989 because of structural damage '
                          'from the 1989 Loma Prieta Earthquake)',
             'id': [498, 499],
             'locations': ['1153-57 Taylor Street',
                           'John Muir Drive (Lake Merced)'],
             'production_company': 'Warner Brothers / Seven Arts\nSeven Arts',
             'release_year': '1968',
             'title': 'Bullitt',
             'writer': 'Alan R. Trustman'}}

推荐阅读