Python:使用两个列表创建一个字典

标签 python list dictionary nested

如何使用 python 使用两个列表来制作字典

list_one_keys = ['key1', 'key2', 'key3', 'key4']

嵌套列表:

list_two_values = [['a1var1', 'a1var2', 'a1var3', 'a1var4'], ['a2var1', 'a2var2', 'a2var3', 'a2var4']]

所需的结果是Python字典:

thisdict = {
  "dict1"{

  "key1": "a1var1",
  "key2": "a1var2",
  "key3": "a1var3",
  "key4": "a1var4"
},
"dict2":{
  "key1": "a2var1",
  "key2": "a2var2",
  "key3": "a2var3",
  "key4": "a2var4"
}


}

谢谢。

最佳答案

您可以尝试结合使用 zipenumeratedict:

result = {'dict{}'.format(index+1):dict(zip(list_one_keys, val)) 
                              for index, val in enumerate(list_two_values)}

输出:

{'dict1': {'key1': 'a1var1',
  'key2': 'a1var2',
  'key3': 'a1var3',
  'key4': 'a1var4'},
 'dict2': {'key1': 'a2var1',
  'key2': 'a2var2',
  'key3': 'a2var3',
  'key4': 'a2var4'}}

关于Python:使用两个列表创建一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59040065/

相关文章:

c# - 用 IEnumerable<> 源填充 Dictionary<>

c++ - boost 。方便的 variables_map。利用在 options_desctription 中指定的类型

python - TensorFlow 数据集 : shuffle before map (map_and_batch)?

python - 如何从两个不同的 numpy 数组创建一个 numpy 数组?

Pythonic 方式并行迭代字典内的列表作为字典

java - 错误: type List does not take parameters

python - 如何匹配列表python中的完全匹配

python - Pandas 过滤/数据缩减(1)有更好的方法吗?2)我做错了什么)

python - 如何使用字典中的重复键生成列表?

python - 通过在 Python 中切片列表来分配值的紧凑方法