如何从python3中的两个列表创建一个dict

时间:2018-01-15 22:34:44

标签: python list dictionary

我有两个list喜欢这些:

first_list=[{
             'a': 2,
             'c': '[53, 94, 58]'
            },
            {
             'a': 3,
             'c': '[81, 43, 38]'
            }]

second_list=[{
            "d" : 2,
            "e" : "name_two",
            "f":True
            },
            {
            "d" : 3,
            "e" : "name_three",
            "f":False
            }]

我如何创建这个'dict':

{"name_two": [53, 94, 58],
 "name_three": [53, 94, 58]}

并将其添加到其他dict,如下所示:

{
"x" : {
    "foo":some_values
    "name_two":[53, 94, 58]
    "name_three":[81, 43, 38]
     }
"y" : ["name_two","name_two"]
}

2 个答案:

答案 0 :(得分:1)

使用dict作为示例字典插入:

>>> dict={"x":{"foo":"some_values"},"y":["name_two","name_two"]}
>>> dict
{'x': {'foo': 'some_values'}, 'y': ['name_two', 'name_two']}
>>> dict['x']={**dict['x'],**{y['e']:x['c'] for x,y in zip(first_list,second_list)}}
>>> dict
{'x': {'foo': 'some_values', 'name_two': '[53, 94, 58]', 'name_three': '[81, 43, 38]'}, 'y': ['name_two', 'name_two']}

在此示例中,数字列表保留为字符串 - 您可以在另一个解决方案中看到将这些字符串转换为整数列表的选项。

答案 1 :(得分:0)

如果你zip()将两个列表放在一起,那么很容易从以下内容中读取字段:

代码:

new_dict = dict((y['e'], json.loads(x['c']))
                for x, y in zip(first_list, second_list))

测试代码:

first_list = [
    {'a': 2, 'c': '[53, 94, 58]'},
    {'a': 3, 'c': '[81, 43, 38]'}
]

second_list = [
    {"d": 2, "e": "name_two", "f": True},
    {"d": 3, "e": "name_three", "f": False}
]

import json
new_dict = dict((y['e'], json.loads(x['c']))
                for x, y in zip(first_list, second_list))

print(new_dict)

我将把它添加到另一个词典作为练习

测试结果:

{'name_two': [53, 94, 58], 'name_three': [81, 43, 38]}