1

I have two lists and an array:

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

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

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

I want to make a nested dictionary out of these.

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

My closest attempt:

 totals_list = totals.tolist()

 dict1 = dict(zip(owners, totals_list))

I cannot find a way to create the nested dictionary I am looking for. Any suggestions?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Caroline.py
  • 293
  • 1
  • 4
  • 16
  • Sorry, I am new to python. Totals are floats or integers? I am assuming. I am learning dictionaries and I want to make some computations to totals such as squaring them, dividing, adding, etc. – Caroline.py Aug 22 '16 at 18:50
  • In your example, totals is of `list` type, which is actually a list of list of integers – Moinuddin Quadri Aug 22 '16 at 18:54

1 Answers1

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

You may also write it in one line using dict comprehension as:

main_dict = {owner: dict(zip(dog, total)) for owner, total in zip(owners, totals)}
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126