简体   繁体   English

创建带有值的字典项目列表

[英]Creating a dictionary with values a list of items

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我得到以下 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但我想要下面的 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]} 

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. collections.defaultdict是专门为此目的而制作的。 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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM