我有一个像这样的词典列表:
listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}]
我想要列出字典中的所有ID。所以,从给定的列表中我会得到列表:
[1,3,5]
它应该是一行。我知道我以前做过这个,我只是忘记了语法......谢谢
答案 0 :(得分:10)
>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}]
>>> [item["id"] for item in listDict]
[1, 3, 5]
答案 1 :(得分:2)
[i['id'] for i in listDict]
答案 2 :(得分:2)
取决于您的数据量有多大,概念上更令人满意且可能更快的方法。
使用pandas包只需使用相同的密钥将密钥称为列标题和组值:
import pandas as pd
listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}]
df = pd.DataFrame(listDict)
# Then just reference the 'id' column to get a numpy array of it
df['id']
# or just get a list
df['id'].tolist()
下面的一些基准测试,熊猫明显优于大数据。小案例使用给定的3个条目,大案例有150k条目:
setup_large = "listDict = [];\
[listDict.extend(({'id':1,'other':2},{'id':3,'other':4},\
{'id':5,'other':6})) for _ in range(50000)];\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(listDict);"
setup_small = "listDict = [];\
listDict.extend(({'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}));\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(listDict);"
method1 = '[item["id"] for item in listDict]'
method2 = "df['id'].tolist()"
import timeit
t = timeit.Timer(method1, setup_small)
print('Small Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_small)
print('Small Method Pandas: ' + str(t.timeit(100)))
t = timeit.Timer(method1, setup_large)
print('Large Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_large)
print('Large Method Pandas: ' + str(t.timeit(100)))
#Small Method LC: 8.79764556885e-05
#Small Method Pandas: 0.00153517723083
#Large Method LC: 2.34853601456
#Large Method Pandas: 0.605192184448
答案 3 :(得分:1)
对于python极客:
import operator
map(operator.itemgetter('id'), listDict)
答案 4 :(得分:0)
[列表Dict中elem的[element ['id']]