使用列表和数组创建嵌套字典

时间:2016-08-22 18:36:31

标签: python arrays list dictionary dict-comprehension

我有两个列表和一个数组:

owners = [ 'Bill', 'Ann', 'Sarah']

dog = ['shepherd', 'collie', 'poodle', 'terrier']

totals = [[5, 15, 3, 20],[3,2,16,16],[20,35,1,2]]

我想用这些来制作嵌套字典。

  dict1 = {'Bill': {'shepherd': 5, 'collie': 15, 'poodle': 3, 'terrier': 20},
           'Ann': {'shepherd': 3, 'collie': 2, 'poodle': 16, 'terrier': 16},
           'Sarah': {'shepherd': 20, 'collie': 35, 'poodle': 1, 'terrier': 2}
          }

我最接近的尝试:

 totals_list = totals.tolist()

 dict1 = dict(zip(owners, totals_list))

我找不到创建我正在寻找的嵌套字典的方法。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

main_dict = {}
for owner, total in zip(owners, totals):
    main_dict[owner] = {}
    for key, value in zip(dog, total):
        main_dict[owner][key] = value

您也可以使用dict comprehension将其作为一行写入:

main_dict = {owner: dict(zip(dog, total)) for owner, total in zip(owners, totals)}