Python:使用列表推导创建字典列表

1 投票
2 回答
3890 浏览
提问于 2025-04-16 06:56

我有一个字典的列表,我想用它来创建另一个稍微修改过的字典列表。

我想做的是:

entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded]

所以我最终会得到另一个字典列表,只是其中一项被修改了。

上面的语法有问题。我该怎么做才能实现我的想法呢?

如果需要我扩展代码示例,请告诉我。

2 个回答

3

这不是你想要的吗?

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
]
4

要为每个项目创建一个新的字典,你需要重新定义一下键:

entries_expanded[:] = [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded]

(如果我理解你想做的事情没错的话)

撰写回答