在不更改旧字典的键的情况下向旧字典添加新键和值? [英] Adding new keys and value to the older dictionary without changing the keys of older dict?
问题描述
我有一本字典,其中包含 URL 作为键,并包含 Open Ports 作为值.即dict200 = {}
I have a dictionary in which it contains URLs as key and Open Ports of their as value. i.e. dict200 = {}
dict200 = {}
{'http://REDACTED1.com': [21, 22, 80, 443, 3306], 'http://www.REDACTED2.com': [80, 443]}
现在我有另一本内容不同的字典,即newerdict = {}
Now I have another dictionary with different content i.e. newerdict = {}
newerdict = {}
newerdict = {'Drupal , ': '7', 'Apache , ': '2.4.34'}
现在请假定在redacted1中使用的是Apache服务器,而在redacted2中使用的是Drupal.
现在我想要的是这样的东西:-
{'http://redacted1.com': [{'apache': '2.4.34' }], 'http://redacted2.com': [{'Drupal': '7'}]}
希望这次我能解释得更好.寻找任何答复.
Hope this time I explained better. Looking for any reply.
-
我能够以某种方式替换值的位置,但是现在我面临的问题是,我无法在字典中访问字典的属性.
Somehow I am able to replace the positions of values, but now the problem I am facing is, I can't access the properties of dict within a dict.
这是完整的输出,
http://redacted1.com : [{'\tApache (web-servers), ': '2.4.34'}]
http://redacted2.com : [{'\tDrupal (cms), ': '7'}]
但是我怎么打印
Apache = 2.4.34
推荐答案
我假设您很少打错字,您可以自己进行格式化. 您需要一个映射来解决此问题.
I assume that you have done few typos, and you can do the formatting by your own. You need a mapping to solve this problem.
这基本上可以解决您的问题
This will mostly solve your problem
dict200 = {'http://redacted1.com': [21, 22, 80, 443, 3306], 'http://redacted2.com': [80, 443]}
newerdict = {'Drupal': '7', 'Apache': '2.4.34'}
mapping = {'http://redacted1.com': 'Apache', 'http://redacted2.com' : 'Drupal'}
new_output = dict()
for key, value in mapping.items():
new_output[key] = [{value: newerdict[value]}]
print(new_output)
使用ordereddict保留python 3.5版的插入顺序. 尽管python 3.7+已内置
Using ordereddict to retain insertion order for python version 3.5. Though python 3.7+ has it built in
from collections import OrderedDict
dict200 = OrderedDict({'http://redacted1.com': [21, 22, 80, 443, 3306], 'http://redacted2.com': [80, 443]})
newerdict = OrderedDict({'Drupal': '7', 'Apache': '2.4.34'})
dict200_index_wise = list(dict200.items())
newerdict_index_wise = list(newerdict.items())
new_output = dict()
for i in range(len(dict200)):
new_output[dict200_index_wise[i][0]] = [{newerdict_index_wise[i][0]:newerdict_index_wise[i][1]}]
print(new_output['http://redacted1.com'][0]['Drupal'])
这篇关于在不更改旧字典的键的情况下向旧字典添加新键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!