首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用项目列表的值创建字典

使用项目列表的值创建字典
EN

Stack Overflow用户
提问于 2021-02-09 14:19:56
回答 1查看 29关注 0票数 1

我正在编写一个程序来创建一个项值的字典,下面是代码

代码语言:javascript
复制
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)

我得到了下面的输出

代码语言:javascript
复制
{'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'} 

但是我想要下面的输出

代码语言:javascript
复制
{'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]} 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-09 14:25:53

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

collections.defaultdict就是专门为此目的而设计的。有关它的更多信息,请阅读here。检查这个代码-

代码语言:javascript
复制
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)
代码语言:javascript
复制
{'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']}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66113938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档