我有一个dicts列表,我想在dicts中单独列出每个键。这些词的关键是相同的。 这是一个例子:
转换这个:
myList = [{'a':0,'b':2},{'a':1,'b':3}]
为:
newList = [[0,1],[2,3]]
答案 0 :(得分:7)
您可以在列表推导中使用class Article < ActiveRecord::Base
def self.published
where(published: true)
end
end
来获取值,然后使用dict.values()
来获取列:
zip
如果您想要列表清单:
>>> zip(*[d.values() for d in myList])
[(0, 1), (2, 3)]
答案 1 :(得分:4)
我发现此网站使用自爆代码: How to convert a list of dictionaries to a list of lists in Python
[[row[key] for row in myList] for key in keylist]
测试:
def bycol_decl(lod, keylist):
return [[row[key] for row in lod] for key in keylist]
if __name__ == "__main__":
lod = [
{'a':1, 'b':2, 'c':3},
{'a':4, 'b':5, 'c':6},
{'a':7, 'b':8, 'c':9},
]
keylist = ['a', 'b', 'c']
print bycol_decl(lod, keylist)
结果:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
答案 2 :(得分:0)
您可以使用setdefault
获取新词典d
,然后打印d.values
d = {}
for e in myList:
for i,j in e.items():
d.setdefault(i, []).append(j)
newList = d.values()
print (newList)
输出:
[[0, 1], [2, 3]]