【问题标题】:Adding new keys and value to the older dictionary without changing the keys of older dict?在不更改旧字典的键的情况下向旧字典添加新键和值?
【发布时间】:2018-05-23 09:36:17
【问题描述】:

我有一本字典,其中包含 URLs 作为键,Open Ports 作为值。即dict200 = {}

dict200 = {}
{'http://REDACTED1.com': [21, 22, 80, 443, 3306], 'http://www.REDACTED2.com': [80, 443]}

现在我有了另一本不同内容的字典,即newerdict = {}

newerdict = {}
newerdict = {'Drupal , ': '7', 'Apache , ': '2.4.34'}

现在请假设 Apache 服务器在 redacted1 中使用,Drupal 在 redacted2 中使用。

现在我想要的是这样的:-

{'http://redacted1.com': [{'apache': '2.4.34' }], 'http://redacted2.com': [{'Drupal': '7'}]}

希望这次我解释得更好。正在寻找任何答复。

编辑:-

我能够以某种方式替换值的位置,但现在我面临的问题是,我无法在 dict 中访问 dict 的属性。

这是完整的输出,

http://redacted1.com : [{'\tApache (web-servers), ': '2.4.34'}]
http://redacted2.com : [{'\tDrupal (cms), ': '7'}]

但是我怎么打印

Apache = 2.4.34

【问题讨论】:

  • 分享所需的输出,因为它不太清楚
  • 你能写一个例子说明你的旧字典在完成你要求的事情后应该是什么样子吗?
  • 好的,我会编辑这个。
  • 请给我想要的输出,我可以给你看。因为它非常大。我不能给你看。 :(

标签: python python-2.7 dictionary


【解决方案1】:

我假设您的拼写错误很少,您可以自己进行格式化。 你需要一个映射来解决这个问题。

这将主要解决您的问题

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 版的插入顺序。 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'])

【讨论】:

  • 您好!感谢您的回答,但是我怎样才能获得映射字典?当你明白了。我可以得到dict200,newerdict,但可以使字典像你的映射字典。这是主要的疑问。
  • 您需要自己制作映射字典,或者您需要找到链接dict200newerdict的任何模式。插入顺序是否相同?我的意思是 redacted1.com 排在第一位,所以它应该有 Drupal 。还是您从其他地方收到的数据?
  • 如果redacted1.com 排在首位并且有Drupal,是否可以不自己制作映射字典?如果可以的话,请根据它更改代码。因为那样我就会有清晰的画面/
  • 是的,那么您可以使用收藏库中的ordereddict,如果您需要,我可以相应地更新答案
  • 使用ordereddict更新了答案
猜你喜欢
  • 2020-08-07
  • 2013-09-12
  • 2015-08-24
  • 2018-05-27
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
相关资源
最近更新 更多