json - 如何在不覆盖数据的情况下加入/合并/更新 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 对象,但我遇到的只是覆盖数据。我不想覆盖任何东西。不太确定如何解决这个问题。
我是否必须为位置字段创建一个空列表并搜索整个数据集以查找相同的标题并获取它们的位置并将它们附加到空列表中,然后最后更新字典?或者当涉及到这样的事情时,有更好的方法/最佳实践吗?
解决方案
这是一种使用简单迭代的方法。
前任:
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'}}
推荐阅读
- javascript - 将 d3 折线图转换为条形图
- sql - 如何将 SYSDATE 转换为如下所示: 2020-09-02-00.00.00 ?甲骨文
- sql - 我正在尝试在 SQL(tera 术语)中创建一个表,但显示的内容与我的预期不同
- api - 尝试使用 Google 表格连接到 Enphase 太阳能 API。无法让代码工作?
- javascript - 想在使用 jquery 的图像之前移动我的价格
- c# - LINQ 根据计数 >1 的另一列获取列
- laravel-5.8 - 租车 Project Laravel 中的日期和时间段之间的可用或不可用汽车
- android - 如何将 Roboto 变体字体系列设置为 android 中的 Textview?
- r - 用于分组变量的 R mgcv 包公式实现中的广义加法混合模型 (GAMM)
- git - 下载了git,安装的安全性怎么样?