我正在编写一个程序来创建一个项值的字典,下面是代码
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)我得到了下面的输出
{'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'} 但是我想要下面的输出
{'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]} 发布于 2021-02-09 14:25:53
原因是您迭代地覆盖了特定键的值,而不是根据需要将它们附加到列表中。
collections.defaultdict就是专门为此目的而设计的。有关它的更多信息,请阅读here。检查这个代码-
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']}https://stackoverflow.com/questions/66113938
复制相似问题