Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle through iterable and keep only relevant elements

Background: I have the following for python 3

data = [{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}, {'name': 'Jim','id_str': '03'}] 
id = ['01','1133', '02', '2222']

Goal: Keep data when id == id_str and append to a list.

The code below appends the first data point [{'id_str': '01', 'name': 'Jon'}] (which is what I want)

id_list = [] 
for d in range(len(data)):
    t = data[d]          
    id_str = t['id_str']       

    if id_str == id[d]: 
        keep = data[d]  
        id_list.append(keep)

Problem: Now I want to move onto the next id in the list '1133'. But since the second id value '1133' does not equal the id_str for the second value in data ({'name': 'Tom','id_str': '02'}, I want it to skip this and move on to the third value in id which is '02'. Since id ('02') is equal to id_str ({'name': 'Tom','id_str': '02'}) I want to append.

I want to continue this process and cycle until all of the id = ['01','1133', '02', '2222'] are checked. This website http://love-python.blogspot.com/2012/03/get-next-element-from-list-in-python.html. suggests that I should add a counter at some point, along with if-else statements but I've tried many times and I'm not sure how.

I would guess my final code would look something like the following

id_list = [] 
for d in range(len(data)):
    t = data[d]          
    id_str = t['id_str']       

    if id_str == id[d]: 
        keep = data[d]  
        id_list.append(keep)

    elif id_str != id_list[d]: 
         skip 
         check next id
    else:
         if no more id to check
         break

Desired final output:

[{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}] 

Question: How do I accomplish these goals:

1) keep and append desired data (when id == id_str)

2) skip unwanted data (when id != id_str)

3) break when finished cycling through id (that is, once all of the elements in id = ['01','1133', '02', '2222'] are indexed and compared to all id_str in data)


1 Answers

Here's one way using a list comprehension.

data = [{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}, {'name': 'Jim','id_str': '03'}] 
ids = ['01','1133', '02', '2222']

res = [d for d in data if d['id_str'] in ids]

# [{'id_str': '01', 'name': 'Jon'}, {'id_str': '02', 'name': 'Tom'}]
like image 99
jpp Avatar answered Apr 29 '26 20:04

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!