在一个列表中使用多个键来迭代字典列表

2024-06-12 01:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一大堆字典。从每个字典中,我想提取一些我事先保存在列表中的键的信息。 我可以用for-循环来完成,但是我的list长度是15504603。它需要很长的时间来处理。我正在寻找替代的方法。你知道吗

我的词典列表(实际上是query_set.QuerySet):

data = [
{'name': 'Alex', 'employee_id': 1110, 'age': 38, 'rank': 'CEO', 'salary': 'unknown'},
{'name': 'Monty', 'employee_id': 1111, 'age': 33, 'rank': 'EO', 'salary': 2400},
{'name': 'John', 'employee_id': 1114, 'age': 32, 'rank': 'EO', 'salary': 2200},
{'name': 'Max', 'employee_id': 1120, 'age': 26, 'rank': 'OA', 'salary': 1200},
{'name': 'Ginee', 'employee_id': 1130, 'age': 28, 'rank': 'OA', 'salary': 1200},
{'name': 'Adam', 'employee_id': None, 'age': 18, 'rank': 'summer_intern', 'salary': None}
]

我要提取的信息是'name''age''rank' 所以我事先列了一张钥匙清单:

info = ['name', 'age', 'rank']

我可以通过执行for循环来完成任务

result = []
result.append(info)
for i in range(len(data)):
    output = [data[i][x] for x in info]
    result.append(output)

最后呢

for item in result:
    print("\t".join(map(str,(item))))

结果是:

name    age rank
Alex    38  CEO
Monty   33  EO
John    32  EO
Max 26  OA
Ginee   28  OA
Adam    18  summer_intern

实际上,在我的列表中有15504603本词典,其中43key : value,这需要花费很长时间来处理。i、 运行约2小时后,e.22661/15504603。你知道吗

有什么理想的方法和节省时间的方法?你知道吗


Tags: 方法nameininfoid列表forage
3条回答

使代码变慢的主要原因是,您正在构建一个巨大的、占用内存的列表,只需进行迭代。您应该在迭代dict列表时逐行直接打印输出:

print(*info, sep='\t')
for record in data:
    print(*(record[key] for key in info), sep='\t')

试试operator.itemgetter

list(map(operator.itemgetter(*info), data))

输出:

[('Alex', 38, 'CEO'),
 ('Monty', 33, 'EO'),
 ('John', 32, 'EO'),
 ('Max', 26, 'OA'),
 ('Ginee', 28, 'OA'),
 ('Adam', 18, 'summer_intern')]

这比原来的循环快6倍:

test = data * 10000
# Given 60,000 dict

%%timeit

result = []
result.append(info)
for i in range(len(test)):
    output = [test[i][x] for x in info]
    result.append(output)
# 36.6 ms ± 314 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit list(map(operator.itemgetter(*info), test))
# 6.92 ms ± 32.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

如果你想用熊猫

import pandas as pd
df = pd.DataFrame(data)
df1 = df.loc[:,['name', 'age', 'rank']]

相关问题 更多 >