I am new to Python and I need some help here.
I need to search a number in dictionary in a list.
I have a long list that looks like this:
userinfo= [{"username": "root", "uid": 0, "try": {"P0000": 100}}, {"username": "Jack", "uid": 1, "try": {"P0000": 100}}, {"username": "Mike", "uid": 3, "try": {"P0000": 100}}, {"username": "Helen", "uid": 7, "try": {"P0000": 100}} ... ]
(the uid is ordered)And I want to know if there is some way that I can search for a uid that equals to some integer, (say 200 for example) without loop over the whole list.
The only way I can search for a 'uid' is to iterate through the whole list to see if there is some uid that equals to the integer and stop if you find a uid larger than the integer or find a uid equal to it. But this is too slow. Or would it be of help if I choose binary search? Thank you very much if you could help.
CodePudding user response:
Try this. Using list comprehension to search for specific id and filtering values which are empty i.e., ''
.
search_id = 3
val = list(filter(None, [value if value['uid'] == search_id else '' for value in userinfo]))
print(val)
Output
[{'username': 'Mike', 'uid': 3, 'try': {'P0000': 100}}]