Python 3.x 创建包含项列表的值的字典

Python 3.x 创建包含项列表的值的字典,python-3.x,Python 3.x,我正在编写一个程序来创建一个项目值列表字典 这是代码 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/2

我正在编写一个程序来创建一个项目值列表字典 这是代码

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]} 
但是我想要下面的输出

{'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]} 

原因是您正在迭代地覆盖特定键的值,而不是根据需要将它们附加到列表中

collections.defaultdict
就是专门为此而设计的。阅读更多关于它的信息。检查此代码-

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)

我得到以下输出{'A&A':'10.1.2.0/24 10.1.0/24授权\响应','AFM':'10.1.3.0/24 10.1.2.0/24私有\授权\请求','OMSS':'10.1.1.0/24 10.1.2.0/24作者\请求'}但我想要以下输出{'A&A':[以A&A开头的流列表],'AFM':[以AFM开头的流列表],'S:[以OMSS开头的流列表]}使用defaultdict将项目附加到每个键的值列表中。检查我的答案以获得解决方案。感谢Akshay,非常感谢随时提供帮助。