Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create one dictonary using 3 lists

I am new to Python and need help creating one dictionary file using three lists.

example:

list 1 = ["private", "private"]
list 2 = ["10.1.1.1", "10.11.11.11"]
list3 = [ "sfc", "gfc"]

my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dict = {}

for s in range(len(list1)):
       dict[list1[s]] =  {list2[s]: list3[s]}
print(dict)

I am getting output as {'private': {'10.1.1.1': 'sfc'}}

but I want output as {'private': {'10.1.1.1': 'sfc'}, {'10.11.11.11': 'gfx'}}

Could somebody help me on how to get in this format?

>Solution :

list1 = ["private", "private"]
list2 = ["10.1.1.1", "10.11.11.11"]
list3 = ["sfc", "gfc"]

my_dict = {}

for s in range(len(list1)):
    if list1[s] not in my_dict:
        my_dict[list1[s]] = []
    my_dict[list1[s]].append({list2[s]: list3[s]})

print(my_dict)

Output:

{'private': [{'10.1.1.1': 'sfc'}, {'10.11.11.11': 'gfc'}]}

It checks for element with same name basically key if present instead of overwriting it appends and update the old one

To get the output for Outer key, Inner key and value:

my_dict = {'private': [{'10.1.1.1': 'sfc'}, {'10.11.11.11': 'gfc'}]}

for key, value_list in my_dict.items():
    for value_dict in value_list:
        for inner_key, inner_value in value_dict.items():
            print(f"Outer Key: {key}, Inner Key: {inner_key}, Value: {inner_value}")

Output:

Outer Key: private, Inner Key: 10.1.1.1, Value: sfc
Outer Key: private, Inner Key: 10.11.11.11, Value: gfc

Please change it as per your need

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading