如何将一个dict添加到多个dict的列表中?Python



我想把json数据转换成键值格式,怎么做?

我的数据

data = { 
"type": "student",
"age": "17",
"sex": "male",
}

预期输出

[ 
{ "type": "student", "key": "age", "value": "17"  },
{ "type": "student", "key": "sex", "value": "male"  },
]

您可以使用一个函数来概括您的输出,以防您的字典中有更多的键需要按原样键入或添加到键值对列表中

def transfrom(data, non_key_value: list, key_value: list):
base = {key: val for key, val in data.items() if key in non_key_value}
ouput = [{**base, **{"key": val, "value": data[val]}} for val in key_value]
return ouput
transfrom(data, non_key_value=["type"], key_value=["age", "sex"])
>>>
[{'type': 'student', 'key': 'age', 'value': '17'},
{'type': 'student', 'key': 'sex', 'value': 'male'}]

我对json不太熟悉,json包中可能有一个函数用于此转换,但这适用于您的数据:

data = { 
"type": "student",
"age": "17",
"sex": "male",
}
out = []
for key, value in data.items():
d = {"type": data["type"]}
if key != "type":
d["key"] = key
d["value"] = value
out.append(d)
out

输出:

[{'type': 'student', 'key': 'age', 'value': '17'},
{'type': 'student', 'key': 'sex', 'value': 'male'}]

这里有一种使用pop方法和|运算符的方法:

data = {"type": "student", "age": "17", "sex": "male"}
base = {"type": data.pop("type")}
output = [base | {"key": key, "value": value} for key, value in data.items()]
print(output)

输出:

[{'type': 'student', 'key': 'age', 'value': '17'}, {'type': 'student', 'key': 'sex', 'value': 'male'}]

这段代码使用pop方法从字典中删除关键字并返回它,这意味着"基本";变为CCD_ 3;数据";变为CCD_ 4。

然后它使用列表理解来迭代"中的剩余键和值;数据";,使用CCD_ 5运算符将它们与"0"中的键/值对组合;基本";每次创建一个新字典。

注意:|操作符是在Python 3.9中引入的。

最新更新