【问题标题】:how to create a dict from two lists in python3 [closed]如何从python3中的两个列表创建一个字典[关闭]
【发布时间】:2018-01-15 22:34:44
【问题描述】:

我有两个像这样的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"]
}

【问题讨论】:

  • How can I create this 'dict'... 好问题,你有什么办法来回答它?
  • 'x''y'some_values 是如何以编程方式生成的? x 的键是否始终是 first_list 中字典中键 'e' 的值?构建应该很容易 - 它正在弄清楚这里的困难逻辑!

标签: python list dictionary


【解决方案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']}

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

【讨论】:

    【解决方案2】:

    如果您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]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2015-03-07
      相关资源
      最近更新 更多