[英]Python: create a list of dictionaries using a list comprehension
我有一个字典列表,我想用它来创建另一个字典列表,并稍加修改。
这是我想做的:
entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded]
因此,我最后得到了另一个词典列表,只是更改了一个条目。
上面的语法已损坏。 我该怎么办?
请让我知道是否应该扩展代码示例。
这不是你想要的吗?
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
]
要为每个字典创建一个新字典,您需要重新声明键:
entries_expanded[:] = [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded]
(无论如何,如果我了解您要正确执行的操作)
使用列表理解
entries_expanded= [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.