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