简体   繁体   English

寻找一种更 Pythonic 的方式来将一个充满字典的列表合并成一个?

[英]Looking for a more pythonic way to merge a list full of dictionaries into one?

I have a list with a bunch of dictionaries that I am trying to combine into one我有一个包含一堆字典的列表,我试图将它们合并为一个

Looks like this...看起来像这样...

[{'name':'name', 'value':'john'}, {'name':'sex', 'value':'male'}, {'name':'color', 'value':'blue'}, {'name':'car', 'value':'toyota'}, {'name':'job', 'value':'cashier'}]

I'm trying to combine them all into one dictionary so that the name value is the key and the value is the value.我试图将它们全部组合成一个字典,以便名称值是键,值是值。 Right now I'm doing something like this and it works fine but I know there is an easier way现在我正在做这样的事情并且它工作正常但我知道有一个更简单的方法

keys = []
vals = []

for item in a:
    if item['name']:
        keys.append(item['name'])

    if item['value']:
        vals.append(item['value'])

md = dict(zip(keys,vals))

Any guidance would be appreciated... thank you任何指导将不胜感激...谢谢

您可以使用字典理解。

new = {i['name']:i['value'] for i in a}

假设你的字典列表被称为 dict_list 你可以使用字典理解如下:

new_dict = { dict['name'] : dict['value'] for dict in dict_list}

您可以直接将dict.values()用于您的特定情况,因为键和值按顺序提供:

dict(d.values() for d in a)

You can do something like this also.你也可以做这样的事情。

input_dict_list = [{'name':'name', 'value':'john'}, {'name':'sex', 'value':'male'}, {'name':'color', 'value':'blue'}, {'name':'car', 'value':'toyota'}, {'name':'job', 'value':'cashier'}]

out_put_dict = {}
for input_dict in input_dict_list:
    out_put_dict[input_dict['name']] = input_dict['value']

print(out_put_dict)

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

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