【问题标题】:Comparing & updating list values inside of dictionaries比较和更新字典内的列表值
【发布时间】:2018-12-03 23:11:34
【问题描述】:
dict1 = {
    "domain1": ["53/tcp,open,domain", "80/tcp,open,http"],
    "domain2": ["22/tcp,open,ssh", "25/tcp,open,smtp", "80/tcp,open,http",
                "443/tcp,open,https"],
    "domain3":["22/tcp,open,ssh"]}

我想比较 dict2dict1 并检查是否有新的键或值(这是开放端口的列表),如果是则更新dict1

dict2 = {
    "domain3":["22/tcp,open,ssh","443/tcp,open,https"],
    "domain4":["80/tcp,open,http", "443/tcp,open,https"],
    "domain5":["80/tcp,open,http", "443/tcp,open,https"]}

我完成了任务的第一部分,即通过比较 dict2dict1 keys 并检查 dict2 中是否有任何新密钥并更新 dict1 来查找任何新密钥.

new_item = {}
for i in dict2.keys():
    if i not in dict1.keys():
        new_item[i] = dict2[i]
        dict1[i] = dict2[i]
print("NEW DOMAINS FOUND : ",new_item)
print(dict1) ## UPDATED with New Domains Found

这是输出:

NEW DOMAINS FOUND :  {
  'domain4': ['80/tcp,open,http', '443/tcp,open,https'],
  'domain5': ['80/tcp,open,http', '443/tcp,open,https']}
 {'domain1': ['53/tcp,open,domain', '80/tcp,open,http'],
  'domain2': ['22/tcp,open,ssh', '25/tcp,open,smtp', '80/tcp,open,http',
              '443/tcp,open,https'],
  'domain3': ['22/tcp,open,ssh'],
  'domain4': ['80/tcp,open,http', '443/tcp,open,https'],
  'domain5': ['80/tcp,open,http', '443/tcp,open,https']}

我需要帮助解决任务的第二部分,即比较 dict2 和 dict1 的值,如果 dict2 中有任何新值,则 用这些值更新 dict1。

如果您查看dict2[domain3]dict1[domain3]dict2[domain3] 中有一个新值,有了这个,现在dict1[domain3] 应该会更新为这些新值。

比较dict2dict1 并更新值/键时我想要的输出:

dict1

{'domain1': ['53/tcp,open,domain', '80/tcp,open,http'],
 'domain2': ['22/tcp,open,ssh', '25/tcp,open,smtp', '80/tcp,open,http',
             '443/tcp,open,https'],
 'domain3': ["22/tcp,open,ssh", "443/tcp,open,https"],
 'domain4': ['80/tcp,open,http', '443/tcp,open,https'],
 'domain5': ['80/tcp,open,http', '443/tcp,open,https']}

如果您需要更多信息或有疑问,请留下评论,我会更新问题。

【问题讨论】:

  • 经验教训:在发布问题之前,始终以非常简单的方式复制问题。

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

如果列表中元素的顺序不重要,可以使用以下方法:

dict3 = {}
for k, v in dict2.items():
    dict3[k] = list(set(dict1.get(k, []) + v))

结果dict3

{'domain3': ['443/tcp,open,https', '22/tcp,open,ssh'], 
 'domain5': ['80/tcp,open,http', '443/tcp,open,https'], 
 'domain4': ['80/tcp,open,http', '443/tcp,open,https']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 2023-01-07
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多