【问题标题】:Dictionary value comparison when values appears as a list值显示为列表时的字典值比较
【发布时间】:2019-09-09 06:40:32
【问题描述】:

我有两个字典,其中值是不同长度的列表,需要比较两个字典的值。作为回报,需要查看 dict1 中的任何列表是否与 dict2 值匹配并打印相应 dict 的键。还可以找到该特定值列表中的不匹配值打印它们

我尝试了多种方法,但得到了这个错误

ValueError:解包的值太多(预计 2 个)

dict1={'apple':[1,2,3,4],'banana':[2,4,7,8],'orange':[5,6,2,4,7]}
dict2={'1':[2,4,7,8,9,3],'2':[5,6,2,4,7,1],'4':[2,3,4,5,6]}

for keys,values in dict1:
    for keys,values in dict2:
        dict1[values]==dict2[values]

结果:对于 dict2,它将选择键并从列表中选择不匹配的值

{'1':[1,7,8,9]}

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    如果您想使用键和值对 dict 进行迭代,请使用 dict.items()。 它返回dict_items(元组列表),其中包括(key, value)

    然后你可以解压它们并在你的 for 循环中使用。

    for key1, val1 in dict1.items():
        for key2, val2 in dict2.items():
            if val1 == val2:
                # now write your required code here
                print('Matched key1 {} key2 {}'.format(key1, key2))
    

    【讨论】:

      【解决方案2】:

      试试这个

      dict1={'apple':[1,2,3,4],'banana':[2,4,7,8],'orange':[5,6,2,4,7]}
      dict2={'1':[2,4,7,8,9,3],'2':[5,6,2,4,7,1],'4':[1,2,3,4]}
      
      for key1, val1 in dict1.items():
          for key2, val2 in dict2.items():
              print("Matching {}:{} and {}:{}".format(key1, val1, key2, val2))
              diff = list(set(val1).symmetric_difference(val2))
              if len(diff) != 0:
                  print("Differences found {}:{}\n".format(key2, diff))
              else:
                  print("The two lists matched\n")
      

      输出

      Matching orange:[5, 6, 2, 4, 7] and 1:[2, 4, 7, 8, 9, 3]
      Differences found 1:[3, 5, 6, 8, 9]
      
      Matching orange:[5, 6, 2, 4, 7] and 2:[5, 6, 2, 4, 7, 1]
      Differences found 2:[1]
      
      Matching orange:[5, 6, 2, 4, 7] and 4:[1, 2, 3, 4]
      Differences found 4:[1, 3, 5, 6, 7]
      
      Matching apple:[1, 2, 3, 4] and 1:[2, 4, 7, 8, 9, 3]
      Differences found 1:[1, 7, 8, 9]
      
      Matching apple:[1, 2, 3, 4] and 2:[5, 6, 2, 4, 7, 1]
      Differences found 2:[3, 5, 6, 7]
      
      Matching apple:[1, 2, 3, 4] and 4:[1, 2, 3, 4]
      The two lists matched
      
      Matching banana:[2, 4, 7, 8] and 1:[2, 4, 7, 8, 9, 3]
      Differences found 1:[3, 9]
      
      Matching banana:[2, 4, 7, 8] and 2:[5, 6, 2, 4, 7, 1]
      Differences found 2:[1, 5, 6, 8]
      
      Matching banana:[2, 4, 7, 8] and 4:[1, 2, 3, 4]
      Differences found 4:[1, 3, 7, 8]
      

      我已更新列表以生成匹配列表的案例,它与此案例 Matching apple:[1, 2, 3, 4] and 4:[1, 2, 3, 4] 匹配。

      【讨论】:

      • 让我试试这个
      猜你喜欢
      • 2023-01-07
      • 2017-12-20
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      相关资源
      最近更新 更多