我有一個很大的字典串列,每個字典都有一個令牌。
large_list = [{"token": "4kj13", "value1": 10, "value2": 20},
{"token": "hm9gm", "value1": 15, "value2": 30}]
我需要通過令牌快速找到字典,例如
print(large_list["4kj13"]["value1"])
有什么優雅的方法嗎?我想我可以創建一個字典標記來索引:
token2index = {"4kj13": 0, "hm9gm": 1}
但如果有更好的解決方案,我會很高興知道。
雖然我可以創建一些中間資料,但我無法更改輸入格式 (json)。
UPD:字典的內容也不簡單,所以串列不能輕易轉換為表格
UPD2:標記是唯一的
uj5u.com熱心網友回復:
轉換list為dict_dict
d = {x["token"]: x for x in large_list}
d["4kj13"]["value1"]
# 10
uj5u.com熱心網友回復:
要獲取特定字典的索引,可以使用next列舉器:
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
如果未找到特定標記,它會以與list.indexValueError相同的方式引發 a :
>>> 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
或者,如果更簡單,您可以使用next默認值:
>>> 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492317.html
上一篇:命名空間字典混淆
