I'm just getting started to Python, and I'm having an hard time figuring out something with if
statements.
Say I have the following two lists:
one = [{'id': '2'}, {'id': 3}]
two = [{'id': '4'}, {'id': 5}]
I want to loop through one
and compare the id
s of one
to two
. Basically, what I want to find is if the two lists share an id
with the same value. In this example, my code should return a Not found
, because 2 is different from 4 and 5, and 3 is different from 4 and 5.
Basically, what i want to do is: check if 2
is equal to any id
of two
, if not, print something, then the same with 3
. In pseudo code it would be like this: IF there is no id
in two
EQUAL TO 2
, PRINT something. Then the same with 3
and so on.
I tried the following:
for x in one:
for y in two:
if x['id'] != y['id']:
print('Not found')
The problem with this code is that it will return four Not found
, because it's comparing every element. Instead, I simply want to check if there is a 2
or a 3
in two
.
Note that you've got what looks like an error in your code, you're using a string for the first ID and an integer for the second one.
There's several ways to check for intersection in python.Here's an article that goes over several different approaches. I like using the set()
type, because it has a helpful built-in method called intersection
. Sets are a bit different than lists, in that they cannot contain duplicates and are automatically sorted.
For example, you if you had a set that contained 1 and 2, ie set1 = set([1,2])
, you could use set1.intersection([2])
to check if 2 was within that set.
Here's how I would implement such functionality in your case (with all keys as integers):
one = [{'id': 2}, {'id': 3}]
two = [{'id': 4}, {'id': 5}]
def flatten(list_of_dicts):
return [item['id'] for item in list_of_dicts]
intersecting_ids = set(flatten(one)).intersection(flatten(two))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.