平铺嵌套的Python字典,压缩密钥 [英] Flatten nested Python dictionaries, compressing keys

查看:345
本文介绍了平铺嵌套的Python字典,压缩密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个字典:

  {'a':1,
'c' 'a':2,
'b':{'x':5,
'y':10}},
'd':[1,2,3]}

您将如何将其平铺成如下所示:



pre> {'a':1,
'c_a':2,
'c_b_x':5,
'c_b_y'
'd':[1,2,3]}


解决方案

基本上与平铺嵌套列表一样,您只需要执行额外的工作即可通过键/值迭代dict,为新字典创建新键,并在最后一步创建字典。 p>

  import collections 

def flatten(d,parent_key ='',sep ='_'):
items = []
for k,v in d.items():
new_key = parent_key + sep + k如果parent_key else k
如果isinstance(v,collections.MutableMapping) :
item.extend(flatten(v,new_key,sep = sep).items())
else:
items.append((new_key,v))
return dict(items)

>>>扁平化({'a':1,'c':{'a':2,'b':{'x':5,'y':10}},'d':[1,2,3] })
{'a':1,'c_a':2,'c_b_x':5,'d':[1,2,3],'c_b_y':10}


Suppose you have a dictionary like:

{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}

How would you go about flattening that into something like:

{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}

解决方案

Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.

import collections

def flatten(d, parent_key='', sep='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.extend(flatten(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}

这篇关于平铺嵌套的Python字典,压缩密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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