Reputation: 198
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.
Upvotes: 2
Views: 106
Reputation: 165
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)
Upvotes: 0
Reputation: 26335
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
Upvotes: 5
Reputation: 1924
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
Upvotes: 0
Reputation: 3048
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]
Upvotes: 1