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

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))


我找不到找到所需嵌套字典的方法。有什么建议么?

最佳答案

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)}

09-25 19:16