【问题标题】:Making a nested dictionary with lists and arrays使用列表和数组制作嵌套字典
【发布时间】:2016-08-22 18:36:31
【问题描述】:

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

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

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

【问题讨论】:

  • 对不起,我是 python 新手。总数是浮点数还是整数?我假设。我正在学习字典,我想对总数进行一些计算,例如平方、除法、加法等。
  • 在你的例子中,totals 是list 类型,它实际上是一个整数列表

标签: python arrays list dictionary dict-comprehension


【解决方案1】:
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)}

【讨论】:

    猜你喜欢
    • 2022-08-16
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多