我有list
个词典。我想从每个词典中提取事先保存在列表中的一些键的信息。
我可以使用for
循环来完成此操作,但是我的list
长度为15,504,603。它需要很长时间才能处理。我正在寻找替代方法。
我的词典列表(实际上是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个词典,其中43个key : value
需要花费很长时间来处理。在运行约2小时后,即22661/15504603。
什么是理想和省时方式?
答案 0 :(得分:0)
如果您想使用熊猫
import pandas as pd
df = pd.DataFrame(data)
df1 = df.loc[:,['name', 'age', 'rank']]
答案 1 :(得分:0)
尝试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)
答案 2 :(得分:0)
让代码变慢的主要原因是,您正在构建一个庞大的,占用大量内存的列表以进行迭代。您应依次遍历字典列表,直接逐行打印输出:
print(*info, sep='\t')
for record in data:
print(*(record[key] for key in info), sep='\t')