【问题标题】:How to append multiple lists to a nested dictionary? [duplicate]如何将多个列表附加到嵌套字典? [复制]
【发布时间】:2018-03-31 13:41:11
【问题描述】:

假设我有三个列表:

list_a = [1,2,3]
list_b = ['a','b','c']
list_c = [4,5,6]

如何创建如下所示的嵌套字典:

dict = {1:{'a':4},2:{'b':5},3:{'c':6}

我正在考虑使用集合模块中的 defaultdict 命令或创建一个类,但我不知道该怎么做

【问题讨论】:

    标签: python list class dictionary


    【解决方案1】:

    您可以利用zip 和字典理解来解决这个问题:

    list_a = [1,2,3]
    list_b = ['a','b','c']
    list_c = [4,5,6]
    final_dict = {a:{b:c} for a, b, c in zip(list_a, list_b, list_c)}
    

    输出:

    {1: {'a': 4}, 2: {'b': 5}, 3: {'c': 6}}
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2020-06-01
      • 1970-01-01
      • 2020-08-10
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      相关资源
      最近更新 更多