简体   繁体   中英

Python remove dictionary in a list by key

Consider the following code:

some_list = [
    {'id' : '3459', 'name' : 'Alice'},
    {'id' : '1112', 'name': 'Bob'}
]
person_id = '3459'
# Search person id in list of dictionaries and return {'id' : '3459', 'name' : 'Alice'}

Knowing the person_id , is it possible to search this some_list by 'id' to grab the whole dictionary? Currently I am doing this with a for loop, but I was curious if there was any other implementations. Thanks to all of those who reply.

You can transform the structure to a nested dictionary, where the key is id . Then you maintain constant O(1) lookups, instead of scanning the list in linear O(N) time.

Example:

data = {
    '3459': {
        'name' : 'Alice'
    },
    '1112': {
        'name': 'Bob'
    }
}

person_id = '3459'

print(data[person_id])
# {'name': 'Alice'}

You could also just have name as a value instead of a dictionary:

data = {
    '3459': 'Alice',
    '1112': 'Bob'
}

person_id = '3459'

print(data[person_id])
# Alice

Note: This assumes no duplicate ids, as @Chris_Rands mentioned in the comments

You can try the following:

[entry for entry in some_list if person_id in entry['id']]

If you want the result not to be a list, try this:

[entry for entry in some_list if person_id in entry['id']][0]
import pandas as pd
import time
start = time.time() 

person_id = '3459'
some_list = [
    {'id' : '3459', 'name' : 'Alice'},
    {'id' : '1112', 'name': 'Bob'}
]

a = pd.DataFrame(some_list) 
a.drop(a.loc[a['id']==person_id].index, inplace=True)
end = time.time()
print(a)
print(end - start)    

output

     id name
1  1112  Bob
0.0030059814453125

This works fine:

some_list = [
{'id' : '3459', 'name' : 'Alice'},
{'id' : '1112', 'name': 'Bob'}
]

person_id = '3459'

result = list(filter(lambda x : x['id'] == person_id, 
some_list))

print(result)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM