I have a large list of dicts, each dict has a token.
large_list = [{"token": "4kj13", "value1": 10, "value2": 20},
{"token": "hm9gm", "value1": 15, "value2": 30}]
I need to quickly find a dictionary by token, something like
print(large_list["4kj13"]["value1"])
Is there any elegant way to do it? I think I can create a dictionary token to index:
token2index = {"4kj13": 0, "hm9gm": 1}
But if there's a better solution, then I would be glad to know.
I can't change the input format (json), though I can create some intermediate data.
UPD: also the content of the dict is not simple, so the list can't be easily transformed to a table
UPD2: tokens are unique
CodePudding user response:
Convert list
of dict
to dict
d = {x["token"]: x for x in large_list}
d["4kj13"]["value1"]
# 10
CodePudding user response:
To get the index of a specific dict, you can use next
with an enumerator:
def get_token(token):
try:
return next(i for i,di in enumerate(large_list) if di['token']==token)
except StopIteration:
raise ValueError
>>> large_list[get_token("4kj13")]
{'token': '4kj13', 'value1': 10, 'value2': 20}
>>> large_list[get_token("4kj13")]['value1']
10
If the specific token is not found, it raises a ValueError
in the same manner as list.index:
>>> large_list[get_token("4kj1")]
Traceback (most recent call last):
File "<stdin>", line 3, in get_token
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in get_token
ValueError
Or you can use next
with a default value if that is simpler:
>>> next((i for i,di in enumerate(large_list) if di['token']=="hm9gm"),-1)
1
>>> next((i for i,di in enumerate(large_list) if di['token']=="hm"),-1)
-1