如果我正确理解您的意图,以下内容应该适合您。这是在 Python 2.7.15rc1 上测试的:
# Example Data
data = {"aaa":[{"etrert":619337442,"home":"werewrw","id": 595506140083,"is_data_real": True},{"etrert":719337432,"home":"filler","id": 695506149983,"is_data_real": True}, {"etrert":719337432,"home":"filler","id": 795506149983,"is_data_real": False}], "bbb":[{"roi":0,"qweqweqe":1,"id": 595506140083},{"roi":1,"qweqweqe":1,"id": 695506149983},{"roi":0,"qweqweqe":1,"id": 59550999983},{"roi":1,"qweqweqe":3,"id": 595506140083}]}
# Create a Filter Function Creator
# If it finds the id, only returns it if "is_data_real" is True
def create_id_filter(id_needed):
def id_filter(d):
if d["id"] == id_needed and d["is_data_real"] == True:
return True
else:
return False
return
return id_filter
# Create a filter for any id number you want
id_filter = create_id_filter(595506140083)
# Filter the "aaa" objects using the filter created above
real_a = filter(id_filter, data["aaa"])
# Use list comprehension to pull out just the ids
a_ids = [x['id'] for x in real_a]
# Use list comprehension to pull all b objects that match the id
b_matches = [x for x in data["bbb"] if x["id"] in a_ids]
print b_matches
# [{'roi': 0, 'qweqweqe': 1, 'id': 595506140083}, {'roi': 1, 'qweqweqe': 3, 'id': 595506140083}]
另外,如果你有一个 id 列表,你可以像这样从 "bbb" 获得所有结果:
def get_b_matches(request_data, id_list):
result = []
for i in id_list:
id_filter = create_id_filter(i)
real_a = filter(id_filter, request_data["aaa"])
a_ids = [x['id'] for x in real_a]
b_matches = [x for x in request_data["bbb"] if x["id"] in a_ids]
result.extend(b_matches)
return result
get_b_matches(data, [595506140083, 695506149983])
# [{'roi': 0, 'qweqweqe': 1, 'id': 595506140083}, {'roi': 1, 'qweqweqe': 3, 'id': 595506140083}, {'roi': 1, 'qweqweqe': 1, 'id': 695506149983}]