[英]iterate list and compare it's values with dict
I am dealing with 1. list of dictionaries and 2. list. 我正在处理1.词典列表和2.列表。 I am trying to:
我在尝试着:
1. iterate through list (list1), 1.遍历列表(list1),
2. Match the list1's value with the ID
of API response, if found- put entire dict in a new_dict 3. else skip 2.如果将list1的值与API响应的
ID
匹配,则将整个dict放入new_dict中。3.否则跳过
API response in Json format: 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
}
...
]
And a list1: 和清单1:
list1=[1500,1501,1211.....]
According to this, 1500 & 1501
is present in list_of_dict so that entire dict will be added in new_dict. 据此,
1500 & 1501
存在于list_of_dict中,因此整个dict将被添加到new_dict中。
My attempt: 我的尝试:
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})
What i see is this code taking only last item of the list and updates the dict.. but in my case, new_dict will contains two dictionaries with id 1500
and 1501
. 我看到的是此代码仅获取列表的最后一项并更新dict ..但就我而言,new_dict将包含ID为
1500
和1501
两个字典。 What i am missing? 我想念什么?
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]
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
Check out the useful and simple filter function built-in to python. 查看python内置的有用和简单的过滤器功能。 It iterates through an iterable (list) and returns only the items that return true for the provided function
迭代一个可迭代的(列表),并且仅返回对于提供的函数返回true的项
In this case, our filtering function is: 在这种情况下,我们的过滤功能为:
lambda x: x['id'] in list1
You can do this with a simple list comprehension, filtering the dicts by whether their id is in the list: 您可以通过简单的列表理解来做到这一点,根据它们的ID是否在列表中来过滤字典:
result = [d for d in list_of_dict if d["id"] in list1]
If your list1
is larger, you might want to turn it into a set
first, so the lookup is faster: 如果
list1
较大,则可能需要先将其转换为set
,这样查找起来会更快:
list1_as_set = set(list1)
result = [d for d in list_of_dict if d["id"] in list1_as_set]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.