简体   繁体   English

如何将嵌套字典更改为字典列表?

[英]How to change a nested dictionary to a list of dictionary?

I have a dictionary like this -我有一本这样的字典-

{'A': {'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0}, 'B': {'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}}

I need this to be changed into a list like this -我需要将其更改为这样的列表-

data = [{"employee_id": 'A', 'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0},
        {"employee_id": 'B', 'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}
        ]

I am sorry if this is a very basic question, I am working on python for the first time in my life.如果这是一个非常基本的问题,我很抱歉,我有生以来第一次在 python 上工作。

Iterate over it:迭代它:

emp_dict = {'A': {'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0},
            'B': {'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}}
emp_list = []
for emp_id, data in emp_dict.items():
    emp_list.append({'employee_id': emp_id, **data})

print(emp_list)

You can also use comprehension instead:您也可以改用理解:

emp_list = [{'employee_id': emp_id, **data} for emp_id, data in emp_dict.items()]

Outputs:输出:

[{'employee_id': 'A', 'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0}, {'employee_id': 'B', 'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}]

If you have just small amounts of data, you can just loop over it and incrementally fill the list.如果您只有少量数据,您可以遍历它并逐步填充列表。 I name your initial dictionary mydict :我将您的初始字典命名为mydict

data = []
for e in mydict.keys():
    entry = mydict[e]
    entry['employee_id'] = e
    data.append(entry)

This will add all employees to a list.这会将所有员工添加到列表中。

You'll have to iterate through all the objects in the main dictionary and add them to your new array.您必须遍历主字典中的所有对象并将它们添加到新数组中。 Here's the sample code for it.这是它的示例代码。

arr = []
for key in main_dict.keys():
  arr.append({
    "employee_id": key,
  }.update(main_dict[key]))

This can also be done with a list comprehension and the dictionary unpacking operation.这也可以通过列表推导字典解包操作来完成。

d = {
    "A": {"c1": 0, "c2": 4, "c3": 0, "c4": 0, "c5": 0},
    "B": {"c1": 1, "c2": 0, "c3": 0, "c4": 0, "c5": 0},
}

l = [{"employee_id": key, **data} for (key, data) in d.items()]

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

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