简体   繁体   English

Python:扁平化字典列表的最佳方法是什么

[英]Python: What is Best Approach for Flattening a list of Dictionary

How can I flatten a List of dictionary with nested dictonaries, say I have the following dict:如何将带有嵌套字典的字典列表展平,例如我有以下字典:

data = [
            { 'Name':'xyx',
            'Age':22,
            'EmpDetails':{'Salary':100,'Job':'Intern','Location':'TER'}
            },
            { 'Name':'abc',
                'Age':23,
                'EmpDetails':{'JoinDate':'20110912','Salary':200,'Job':'Intern2','Location':'TER2'}
            },
            {'Name':'efg',
                'Age':24,
                'EmpDetails':{'JoinDate':'20110912','enddate':'20120912','Salary':300,'Job':'Intern3','Location':'TER3'}
            }
       ]

i would need the EmpDetails Node removed and move its values one level up, like below我需要删除 EmpDetails 节点并将其值向上移动一级,如下所示

data = [
            { 'Name':'xyx','Age':22,'Salary':100,'Job':'Intern','Location':'TER'},
            { 'Name':'abc','Age':23,'JoinDate':'20110912','Salary':200,'Job':'Intern2','Location':'TER2'},
            {'Name':'efg','Age':24,'JoinDate':'20110912','enddate':'20120912','Salary':300,'Job':'Intern3','Location':'TER3'}
       ]

i am this now using below, is there any faster way of doing this?我现在在下面使用,有没有更快的方法?

newlist = []
for d in data:
    empdict ={}
    for key, val in d.items():
        if(key!='EmpDetails'):
            empdict[key] = val
        if(key=='EmpDetails'):
            for key2, val2 in val.items():
                empdict[key2] = val2
    newlist.append(empdict)

This is one approach using dict.update and .pop这是使用dict.update.pop一种方法

Ex:前任:

data = [
            { 'Name':'xyx',
            'Age':22,
            'EmpDetails':{'Salary':100,'Job':'Intern','Location':'TER'}
            },
            { 'Name':'abc',
                'Age':23,
                'EmpDetails':{'JoinDate':'20110912','Salary':200,'Job':'Intern2','Location':'TER2'}
            },
            {'Name':'efg',
                'Age':24,
                'EmpDetails':{'JoinDate':'20110912','enddate':'20120912','Salary':300,'Job':'Intern3','Location':'TER3'}
            }
       ]

for i in data:
    i.update(i.pop("EmpDetails"))
print(data)

Output:输出:

[{'Age': 22, 'Job': 'Intern', 'Location': 'TER', 'Name': 'xyx', 'Salary': 100},
 {'Age': 23,
  'Job': 'Intern2',
  'JoinDate': '20110912',
  'Location': 'TER2',
  'Name': 'abc',
  'Salary': 200},
 {'Age': 24,
  'Job': 'Intern3',
  'JoinDate': '20110912',
  'Location': 'TER3',
  'Name': 'efg',
  'Salary': 300,
  'enddate': '20120912'}]

One line method, maybe a little tricky.单行方法,可能有点棘手。

data = [
    {
        "Name": "xyx",
        "Age": 22,
        "EmpDetails": {"Salary": 100, "Job": "Intern", "Location": "TER"},
    },
    {
        "Name": "abc",
        "Age": 23,
        "EmpDetails": {
            "JoinDate": "20110912",
            "Salary": 200,
            "Job": "Intern2",
            "Location": "TER2",
        },
    },
    {
        "Name": "efg",
        "Age": 24,
        "EmpDetails": {
            "JoinDate": "20110912",
            "enddate": "20120912",
            "Salary": 300,
            "Job": "Intern3",
            "Location": "TER3",
        },
    },
]

# only python3.5+
res = [{**item.pop("EmpDetails", {}), **item} for item in data]

I'd prefer using json_normalize() method from pandas library since it would be an elegant solution and had no effect on readability of your code.我更喜欢使用 pandas 库中的json_normalize()方法,因为这将是一个优雅的解决方案,并且对代码的可读性没有影响。

Examples can bee seen here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html示例可以在这里看到: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM