【问题标题】:Combine two dictionaries with list values from one dictionary linked to keys of another将两个字典与一个字典中的列表值结合起来,该字典链接到另一个字典的键
【发布时间】:2018-08-23 18:21:02
【问题描述】:

我有两个 dicts ,我想首先将键和值与输入 2 进行比较:

像键 ope1 这样的示例与第二个输入进行比较并输出一个元组 ('x','1) 作为输出中的键

我们将值 'y' 和 'z' 与显示 y --> 2 和 z--> 4 的第二个列表进行比较,并生成一个元组列表 [('y'-'2'), ('z','4')] 如示例所示

input1 = {'x':['y','z'], 'w':['m','n']}

input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}

#output = {('x','1'):[('y','2'),('z','4')], ('w','3'): [('m','100'),('n','200')]}

【问题讨论】:

    标签: python loops dictionary iterator


    【解决方案1】:

    您可以为此使用字典推导:

    i1 = {'x':['y','z'], 'w':['m','n']}
    i2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
    
    d = {(k, i2[k]): [(i, i2[i]) for i in v] for k, v in i1.items()}
    
    # {('w', '3'): [('m', '100'), ('n', '200')],
    #  ('x', '1'): [('y', '2'), ('z', '4')]}
    

    【讨论】:

      【解决方案2】:

      一种方法是遍历您的 input1 字典并形成所需的输出。

      演示

      input1 = {'x':['y','z'], 'w':['m','n']}
      input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
      
      d = {}
      for k,v in input1.items():   #iterate over input1
          d[(k, input2[k])] = []   #Create key and list as value.
          for i in v:
              d[(k, input2[k])].append((i, input2[i]))
      
      print(d)
      

      输出:

      {('x', '1'): [('y', '2'), ('z', '4')], ('w', '3'): [('m', '100'), ('n', '200')]}
      

      【讨论】:

        【解决方案3】:

        有很多方法可以做到这一点:

        input1 = {'x':['y','z'], 'w':['m','n']}
        
        input2 = {'x':'1','y':'2','w':'3', 'z':'4','m':'100','n':'200'}
        

        defaultdict 在一行

        import collections 
        
        d=collections.defaultdict(list)
        [d[(i,input2[i])].append((m,input2[m])) for i,j in input1.items() for m in j]
        

        没有任何导入:

         new_dict={}
            for i,j in input1.items():
                for m in j:
                    if (i,input2[i]) not in new_dict:
                        new_dict[(i,input2[i])]=[(m,input2[m])]
                    else:
                        new_dict[(i, input2[i])].append((m,input2[m]))
            print(new_dict)
        

        输出:

        {('w', '3'): [('m', '100'), ('n', '200')], ('x', '1'): [('y', '2'), ('z', '4')]}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-06-23
          • 1970-01-01
          • 1970-01-01
          • 2021-03-30
          • 1970-01-01
          • 1970-01-01
          • 2017-07-23
          相关资源
          最近更新 更多