gpt4 book ai didi

python - 使用列表和数组制作嵌套字典

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:46 25 4
gpt4 key购买 nike

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

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

关于python - 使用列表和数组制作嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com