我正在查询数据库,以便它返回如下内容:
[{"Name": "John", "hair_color": "Brown", "eye_color": "Blue"},
{"Name": "Sally", "hair_color": "Red", "eye_color": "Green"},
{"Name": "Bill", "hair_color": NULL, "eye_color": "Blue"}
]
我如何遍历该词典列表以输出如下内容:
[{"John": {"Attribute": "hair_color", "Value": "Brown"}},
{"John": {"Attribute": "eye_color", "Value": "Blue"}},
{"Sally": {"Attribute": "hair_color", "Value": "Red"}},
{"Sally": {"Attribute": "eye_color", "Value": "Green"}},
{"Bill": {"Attribute": "hair_color", "Value": NULL}},
{"Bill": {"Attribute": "eye_color", "Value": "Blue"}},
]
答案 0 :(得分:3)
这是更简洁,更快速的代码版本
input_list = [{"Name": "John", "hair_color": "Brown", "eye_color": "Blue"},
{"Name": "Sally", "hair_color": "Red", "eye_color": "Green"},
{"Name": "Bill", "hair_color": None, "eye_color": "Blue"}]
output_list = [{person['Name']: {'Attribute': attr_key, 'Value': person[attr_key]}}
for person in input_list for attr_key in person if attr_key != 'Name']
print(output)
输出:
[{'John': {'Attribute': 'hair_color', 'Value': 'Brown'}},
{'John': {'Attribute': 'eye_color', 'Value': 'Blue'}},
{'Sally': {'Attribute': 'hair_color', 'Value': 'Red'}},
{'Sally': {'Attribute': 'eye_color', 'Value': 'Green'}},
{'Bill': {'Attribute': 'hair_color', 'Value': None}},
{'Bill': {'Attribute': 'eye_color', 'Value': 'Blue'}}]
带循环的版本
# Empty output list
output_list2 = []
# Loop through persons dict
for person in input_list:
# Save person name
name = person['Name']
# Loop through every attr the person
for attr_key in person:
# If arribute not Name add new dict to output list
if attr_key != 'Name':
output_list2.append({name: {'Attribute': attr_key, 'Value': person[attr_key]}})
print(output_list2)
输出版本2:
[{'John': {'Attribute': 'hair_color', 'Value': 'Brown'}},
{'John': {'Attribute': 'eye_color', 'Value': 'Blue'}},
{'Sally': {'Attribute': 'hair_color', 'Value': 'Red'}},
{'Sally': {'Attribute': 'eye_color', 'Value': 'Green'}},
{'Bill': {'Attribute': 'hair_color', 'Value': None}},
{'Bill': {'Attribute': 'eye_color', 'Value': 'Blue'}}]
答案 1 :(得分:-1)
>>> lst = [{"Name": "John", "hair_color": "Brown", "eye_color": "Blue"},
... {"Name": "Sally", "hair_color": "Red", "eye_color": "Green"},
... {"Name": "Bill", "hair_color": "NULL", "eye_color": "Blue"}
... ]
>>>
>>> res = [{d['Name']: {"Attribute": k, "Value": v}} for d in lst for k,v in d.items() if k!='Name']
>>>
>>> pprint(res)
[{'John': {'Attribute': 'hair_color', 'Value': 'Brown'}},
{'John': {'Attribute': 'eye_color', 'Value': 'Blue'}},
{'Sally': {'Attribute': 'hair_color', 'Value': 'Red'}},
{'Sally': {'Attribute': 'eye_color', 'Value': 'Green'}},
{'Bill': {'Attribute': 'hair_color', 'Value': 'NULL'}},
{'Bill': {'Attribute': 'eye_color', 'Value': 'Blue'}}]