Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将嵌套字典更改为字典列表?_Python - Fatal编程技术网

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

Python 如何将嵌套字典更改为字典列表?,python,Python,我有一本这样的字典- {'A': {'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0}, 'B': {'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}} data = [{"employee_id": 'A', 'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0}, {"employee_id": 'B', 'c1': 1,

我有一本这样的字典-

{'A': {'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0}, 'B': {'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}}
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}
        ]
我需要把它改成这样的列表-

{'A': {'c1': 0, 'c2': 4, 'c3': 0, 'c4': 0, 'c5': 0}, 'B': {'c1': 1, 'c2': 0, 'c3': 0, 'c4': 0, 'c5': 0}}
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}
        ]

如果这是一个非常基本的问题,我很抱歉,这是我有生以来第一次使用python。

如果您只有少量数据,您可以循环使用它并以增量方式填充列表。我给您的初始词典命名为mydict
mydict

data = []
for e in mydict.keys():
    entry = mydict[e]
    entry['employee_id'] = e
    data.append(entry)
这会将所有员工添加到列表中。

对其进行迭代:

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)
你也可以用理解来代替:

产出:

[{'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}]

您必须遍历主字典中的所有对象,并将它们添加到新数组中。下面是它的示例代码

arr=[]
对于主目录键()中的键:
arr.append({
“员工id”:密钥,
}.更新(主目录[键])

这也可以通过and操作完成

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