如何在python中合并具有相同键的嵌套字典 [英] How to merge nested dictionary having same keys in python

查看:75
本文介绍了如何在python中合并具有相同键的嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据结构:

I have a data structure like this:

[ {'SNAPSHOT': {'SnapshotVersion': '304'}},

  {'SNAPSHOT': {'SnapshotCreationDate': '2015-06-21 17:33:41'}},


  {'CafeData': {'CafeVersion': '2807'}}, 

  {'CafeData': {'IsSoftwareOnly': '1'}}, 

  {'CafeData'{'IsPassportTCPIP': '1'}} 

  {'SNAPSHOT': {'SnapshotVersion': '777'}},

  {'SNAPSHOT': {'SnapshotCreationDate': '2017-07-27 17:37:47'}},]

输出应如下所示:

 [ {'SNAPSHOT': {'SnapshotVersion': '304','SnapshotCreationDate': '2015-06-21 17:33:41'}},

   {'CafeData': {'CafeVersion': '2807','IsSoftwareOnly': '1','IsPassportTCPIP': '1'}} 
 
   {'SNAPSHOT': {'SnapshotVersion': '777','SnapshotCreationDate': '2017-07-27 17:37:47'}},
]

或输出应如下所示:

[ {'SNAPSHOT': {'SnapshotVersion': ['304','777'],
                'SnapshotCreationDate': ['2015-06-21 17:33:41','2017-07-27 17:37:47']}},

   {'CafeData': {'CafeVersion': '2807','IsSoftwareOnly': '1','IsPassportTCPIP': '1'}} 

]

推荐答案

可以使用for循环并跟踪最后合并的键.

Could use a for loop and keep track of the last key that was merged.

from pprint import pprint

data = [
    {"SNAPSHOT": {"SnapshotVersion": "304"}},
    {"SNAPSHOT": {"SnapshotCreationDate": "2015-06-21 17:33:41"}},
    {"CafeData": {"CafeVersion": "2807"}},
    {"CafeData": {"IsSoftwareOnly": "1"}},
    {"CafeData": {"IsPassportTCPIP": "1"}},
    {"SNAPSHOT": {"SnapshotVersion": "777"}},
    {"SNAPSHOT": {"SnapshotCreationDate": "2017-07-27 17:37:47"}},
]

last_key = None
grouped = []
for value in data:
    # Easy way to get the key of a dict with one key
    curr_key = next(iter(value))
    # Decide if we should work on the next entry
    if last_key is None or curr_key != last_key:
        grouped.append(value)
    else:
        # update the last value in the group with the new data
        grouped[-1][curr_key].update(value[curr_key])
    # Move to the next item
    last_key = curr_key

pprint(grouped)

[{'SNAPSHOT': {'SnapshotCreationDate': '2015-06-21 17:33:41',
               'SnapshotVersion': '304'}},
 {'CafeData': {'CafeVersion': '2807',
               'IsPassportTCPIP': '1',
               'IsSoftwareOnly': '1'}},
 {'SNAPSHOT': {'SnapshotCreationDate': '2017-07-27 17:37:47',
               'SnapshotVersion': '777'}}]

选项2相似,但是对于分组,我只使用字典.在这种情况下,您不需要知道最后一个键.

Option 2 is similar, but for grouped I would just use a dict. In this case you don't need to know about the last key.

如果嵌套字典中有键冲突,还需要对如何合并vales做一些假设.

Also you need to make some assumptions on how to merge vales if there are key collisions in the nested dict.

grouped = {}
for value in data:
    curr_key = next(iter(value))
    curr_value = value[curr_key]
    group = grouped.setdefault(curr_key, {})

    for sub_key, sub_value in curr_value.items():
        # check if you need to merge
        if sub_key in group:
            # If the key is already present, but is not a list, make it one
            if not isinstance(group[sub_key], list):
                group[sub_key] = [group[sub_key]]
            # Add the new value to the list
            group[sub_key].append(sub_value)
        else:
            # Otherwise just copy it over
            group[sub_key] = sub_value

pprint(grouped)

{'CafeData': {'CafeVersion': '2807',
              'IsPassportTCPIP': '1',
              'IsSoftwareOnly': '1'},
 'SNAPSHOT': {'SnapshotCreationDate': ['2015-06-21 17:33:41',
                                       '2017-07-27 17:37:47'],
              'SnapshotVersion': ['304', '777']}}

这篇关于如何在python中合并具有相同键的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆