迭代列表并将其与dict进行比较

时间:2016-01-22 21:54:27

标签: python list python-2.7 dictionary

我正在处理1.字典列表和2.列表。我想:
1.遍历列表(list1),
2.将list1的值与API响应的ID匹配,如果找到 - 将整个dict放入new_dict 3.否则跳过

Json格式的API响应:

   list_of_dict=[{"id":1500,
      "f_name": "alex",
       "age": 25
      },

      {"id" :1501,
       "f_name":"Bob",
       "age": 30
      },
      {"id" :1600,
       "f_name":"Charlie",
       "age": 35
      }
      ...
     ]

还有一个清单1:

list1=[1500,1501,1211.....]

根据这一点,list_of_dict中存在1500 & 1501,因此整个dict将被添加到new_dict中。

我的尝试:

new_dict=dict()
for i,val in enumerate(list1):
    #assuming val found in dict
    #so put it in new dict
    print i ,"=",val
    new_dict.update({"id": val,"name":name, "age":age})

我看到的是这段代码只占用了列表的最后一项并更新了dict ..但在我的情况下,new_dict将包含两个ID为15001501的词典。我错过了什么?

3 个答案:

答案 0 :(得分:0)

    list_of_dict = [{"id":1500,
                     "f_name": "alex",
                     "age": 25
                     },

                     {"id" :1501,
                      "f_name":"Bob",
                      "age" 30
                     },
                     {"id" :1600,
                      "f_name":"Charlie",
                      "age" 35
                     }
                     ...
                  ]

dicts = {d['id']:d for d in list_of_dict}
list1=[1500,1501,1211.....]

answer = [dicts[k] for k in list1 if k in dicts]

答案 1 :(得分:0)

list_of_dict = [{"id":1500,
                     "f_name": "alex",
                     "age": 25
                     },

                     {"id" :1501,
                      "f_name":"Bob",
                      "age": 30
                     },
                     {"id" :1600,
                      "f_name":"Charlie",
                      "age": 35
                     }
                  ]

list1=[1500,1501,1211]

ret = filter(lambda x: x['id'] in list1, list_of_dict)
print ret

查看python内置的有用且简单的过滤器功能。它遍历一个iterable(list)并只返回为提供的函数返回true的项

在这种情况下,我们的过滤功能是:

lambda x: x['id'] in list1

答案 2 :(得分:0)

您可以使用简单的列表理解来完成此操作,根据他们的ID是否在列表中来过滤dicts:

result = [d for d in list_of_dict if d["id"] in list1]

如果您的list1较大,您可能希望先将其变为set,以便查找速度更快:

list1_as_set = set(list1)
result = [d for d in list_of_dict if d["id"] in list1_as_set]