【问题标题】:find the same key from the dictionary and place the subject in a new dictionary从字典中找到相同的键并将主题放在新字典中
【发布时间】:2020-08-07 19:11:25
【问题描述】:

我有来自服务器的 2 个不同的响应,具有相同的键,我将它们转换为字典:

dict1 = {'111': ['one', 1],
         'bla': ['blaa', blaa],
         '222': ['two', 2],
         'bla1: ['bla2', bla3],
         '333': ['three', 3],
}

dict2 = {'111': ['no matter what is here1'],
         'AAA': ['no matter what is here2'],
         '222': ['no matter what is here3'],
         'BBB': ['no matter what is here4'],
         '333': ['no matter what is here5'],
}

dict2 中存储什么值对我来说并不重要,我需要让 dict2 在 dict1 中找到相同的键,并将 dict1 中的完整项放入新的 dict3 字典中。

输出应该是这样的:

dict3 = {'111': ['one', 1],
         '222': ['two', 2],
         '333': ['three', 3], 

粗略地说,dict2的key是指针,dict1中的item要放入dict3

解决方案不是 def () 对我来说很重要

【问题讨论】:

  • {key:dict1[key] for key in set(dict1.keys())&set(dict2.keys())} 适合你吗?
  • @Arjun Muraleedharan 是的.. 谢谢

标签: python python-3.x dictionary


【解决方案1】:

这是你要找的吗?

dict1 = {'111': ['one', 1],
         'bla': ['blaa', 'blaa'],
         '222': ['two', 2],
         'bla1': ['bla2', 'bla3'],
         '333': ['three', 3],
}

dict2 = {'111': ['no matter what is here1'],
         'AAA': ['no matter what is here2'],
         '222': ['no matter what is here3'],
         'BBB': ['no matter what is here4'],
         '333': ['no matter what is here5'],
}


dict3 = {k: dict1.get(k) for k in dict2.keys() if k in dict1.keys()}

print(dict3)
# {'111': ['one', 1], '222': ['two', 2], '333': ['three', 3]}

【讨论】:

    【解决方案2】:

    所以您想要来自dict2 的键和来自dict1 的相应值(如果存在)?

    这样的事情应该可以工作:

    dict3 = {key:dict1.get(key) for key in dict2.keys() if dict1.get(key, None) is not None}
    

    【讨论】:

      【解决方案3】:

      遍历dict2中的键,检查该键是否在dict1中,是否放入dict 3中。

      dict3 = {}
      
      for k, _ in dict2.items():
          if k in dict1.keys():
              dict3[k] = dict1[k]
      

      【讨论】:

        【解决方案4】:

        此处将生成dict3,其中所有来自dict1 的值共享一个来自dict2 的键。

        dict3 = {}
        
        for key in dict2.keys():
            if key in dict1:
                dict3[key] = dict1[key]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多