Reputation: 15
i am working on program to create a dictionary of list of items values here is code
list_4 = ['A&A OMSS 10.1.2.0/24 10.1.1.0/24 Authorisation_Response', 'A&A OMSS 10.1.2.0/24 10.1.1.0/24 Authentication_Response', 'OMSS A&A 10.1.1.0/24 10.1.2.0/24 Authorsiation_Request', 'OMSS A&A 10.1.1.0/24 10.1.2.0/24 Authentication_Request', 'A&A AFM 10.1.2.0/24 10.1.3.0/24 Authorisation_Response', 'AFM A&A 10.1.3.0/24 10.1.2.0/24 Priviliged_Authentication_Request', 'A&A AFM 10.1.2.0/24 10.1.3.0/24 Privilged_Authentication_Response', 'AFM A&A 10.1.3.0/24 10.1.2.0/24 Priviliged_Authorisation_Request', 'A&A AFM 10.1.2.0/24 10.1.3.0/24 Authorisation_Response']
dict_1 = {'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
for key, value in dict_1.items():
for i in list_4:
src_sys, dst_sys, src, dst, fun = i.split()
if src_sys.strip() == key.strip():
dict_2[key] = (src+" "+dst+" "+fun)
i am getting the below output
{'A&A': '10.1.2.0/24 10.1.1.0/24 Authorisation_Response', 'AFM': '10.1.3.0/24 10.1.2.0/24 Priviliged_Authorisation_Request', 'OMSS': '10.1.1.0/24 10.1.2.0/24 Authorsiation_Request'}
but i want the below output
{'A&A': [list of flows that start with A&A], 'AFM': [list of flows that start with AFM]', 'OMSS': [list of flows that start with OMSS]}
Upvotes: 1
Views: 35
Reputation: 19322
The reason is that you are overwriting the value for the specific key iteratively instead of appending them to a list as you require.
collections.defaultdict
is made specifically for this purpose. Read more about it here. Check this code -
from collections import defaultdict
dict_2 = defaultdict(list) #dictionary where each value is an empty list by default
for key, value in dict_1.items():
for i in list_4:
src_sys, dst_sys, src, dst, fun = i.split()
if src_sys.strip() == key.strip():
dict_2[key].append(src+" "+dst+" "+fun) #<---- append to the key's value
dict_2 = dict(dict_2)
{'OMSS': ['10.1.1.0/24 10.1.2.0/24 Authorsiation_Request',
'10.1.1.0/24 10.1.2.0/24 Authentication_Request'],
'A&A': ['10.1.2.0/24 10.1.1.0/24 Authorisation_Response',
'10.1.2.0/24 10.1.1.0/24 Authentication_Response',
'10.1.2.0/24 10.1.3.0/24 Authorisation_Response',
'10.1.2.0/24 10.1.3.0/24 Privilged_Authentication_Response',
'10.1.2.0/24 10.1.3.0/24 Authorisation_Response'],
'AFM': ['10.1.3.0/24 10.1.2.0/24 Priviliged_Authentication_Request',
'10.1.3.0/24 10.1.2.0/24 Priviliged_Authorisation_Request']}
Upvotes: 1