【问题标题】:Comparing the values inside a list with dictionary values inside the list将列表中的值与列表中的字典值进行比较
【发布时间】:2018-06-20 08:41:59
【问题描述】:

我在一个列表中有一本字典:

list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]

我有一个清单:

list2 = ['Name','Number']

如何检查 list2 中的值是否存在于 list1 中。 如果存在,我需要列出 Value

例如:如果存在 Name ,则打印 "John"

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    请同时阅读 cmets:

    for i in list2: #iterate through list2
            for j in list1: #iterate through list of dictinaries
                if i in j.values(): #if value of list2 present in the values of a dict then proceed
                    print(j['Value'])
    

    【讨论】:

      【解决方案2】:

      您可以使用for 循环。请注意,我使用 set 代替 list2 在循环中启用 O(1) 查找。

      list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
      
      list2 = {'Name', 'Number'}
      
      for item in list1:
          if item['Key'] in list2:
              print(item['Value'])
      
      # John
      # 17        
      

      【讨论】:

        【解决方案3】:

        这是我的单行样式建议,恕我直言,易于阅读。

        1. 结果排序与list1相同的第一个解决方案:

          list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
          list2 = ['Name','Number']
          
          values = [x['Value'] for x in list1 if x['Key'] in list2]
          
          print(values)
          # ['John', '17']
          
        2. 第二个解决方案,结果按list2 相同的顺序排序:

          list1 = [{'Value': 'John','Key': 'Name'}, {'Value':'17','Key': 'Number'}]
          list2 = ['Number', 'Name']
          
          values = [x['Value'] for v in list2 for x in list1 if x['Key'] == v]
          
          print(values)
          # ['17', 'John']
          

        【讨论】:

          【解决方案4】:

          首先,我会将您的 list1 转化为它的命运:一本字典。

          dict1 = {d['Key']: d['Value'] for d in list1}
          

          然后你可以简单地循环 list2 并在键存在时打印值:

          for key in list2:
              if key in dict1:
                  print(dict1[key])
          

          打印出来:

          John
          17
          

          【讨论】:

            猜你喜欢
            • 2019-03-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多