[英]Fastest way to filter for certain keys from dictionaries which are stored in a list of dictionaries which is in turn stored in a dictionary
我正在尋找從“外部”字典內的列表中的“內部”字典中過濾某些鍵的最快方法,這是一種棘手的數據結構。
數據結構(輸入)如下所示:所有內部字典具有相同的鍵,但列表可以具有不同數量的字典。
d = {1:[{1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}],
2:[{1:33 ,2:33, 3:33, 4:33}],
3:[{1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}]}
我想要的 output 是相同的結構,但只有內部字典鍵 1 和 2,我不再需要 3 和 4:
d_new = {1: [{1: 33, 2: 33}, {1: 33, 2: 33}, {1: 33, 2: 33}],
2: [{1: 33, 2: 33}],
3: [{1: 33, 2: 33}, {1: 33, 2: 33}, {1: 33, 2: 33}]}
到目前為止,我有兩種解決問題的方法,但速度很慢:
d_new = {n: [{1: d[1], 2: d[2]} for d in d[n]] for n in d.keys()}
d_new = {}
keys = d.keys()
for key in keys:
storage = []
for x in d[key]:
storage.append({1: x[1], 2: x[2]})
d_new[key] = storage
它們都解決了這個問題,但是在應用於大型詞典時非常慢,所以我正在尋找一種更快更有效的方法,也許也可以在這里應用某種並行化。 很高興有任何幫助!
from copy import deepcopy
d = {1:[{1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}],
2:[{1:33 ,2:33, 3:33, 4:33}],
3:[{1:33 ,2:33, 3:33, 4:33}, {1:33 ,2:33, 3:33, 4:33}]}
d_new = deepcopy(d) #Done so that we don't run into issues with list items
d_items = list(d_new.items())
for i in d_items:
for j in i[1]:
pop_l = [] #Created a list of entries to pop since popping them while in the for loop changes the loop length and gives a runtime error
for k in j:
if k > 2:
pop_l.append(k)
for x in pop_l: #Popping all unwanted keys
j.pop(x)
print(d_new)
{1: [{1: 33, 2: 33}, {1: 33, 2: 33}, {1: 33, 2: 33}], 2: [{1: 33, 2: 33}], 3: [{1: 33, 2: 33}, {1: 33, 2: 33}]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.