Python:使用列表理解创建词典列表
问题描述:
我有一个词典列表,我想用它来创建另一个词典列表,稍作修改。Python:使用列表理解创建词典列表
这就是我想做的事:
entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded]
所以我结束了字典的另一个列表,只需用一个条目改变。
上述语法已损坏。我该怎么做我想要的?
请让我知道我是否应该展开代码示例。
答
要为每个字典创建一个新的字典,您需要重新键:
entries_expanded[:] = [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded]
(如果我已经理解你正在尝试做的是正确的,无论如何)
+0
是的。谢谢! – AP257 2010-11-12 10:18:55
答
这不是你想要的吗?
entries_expanded[:] = [
dict((entry['id'], myfunction(entry['supplier'])))
for entry in entries_expanded
]
你可以把它理解为创建的元组,然后列表的理解,使词典发电机:
entryiter = ((entry['id'], entry['supplier']) for entry in entries_expanded)
tupleiter = ((id, myfunction(supplier)) for id, supplier in entryiter)
entries_expanded[:] = [dict(t) for t in tupleiter]
或者,它是作为对方的回答表明:
entryiter = ((entry['id'], entry['supplier']) for entry in entries_expanded)
tupleiter = ((id, myfunction(supplier)) for id, supplier in entryiter)
entries_expanded[:] = [
dict((('id', id), ('supplier', supplier)))
for id, supplier in tupleiter
]
你正在使用哪个版本的Python? – 2010-11-11 20:31:42
你能提供一个输入数据样本以及你期望输出的样子吗? – 2010-11-11 20:33:06