- 1 year ago 72
Python Question

Making a nested dictionary with lists and arrays

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?

Answer Source
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)}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download