简体   繁体   中英

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.

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 :

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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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