Python: create a list of dictionaries using a list comprehension
I have a list of dictionaries, and I want to use it to create another list of dictionaries, slightly amended.
Here's what I want to do:
entries_expanded[:] = [{entry['id'], myfunction(entry['supplier'])} for entry in entries_expanded]
So I end up with another list of dictionaries, just with one entry altered.
The syntax above is broken. How can I do what I want?
Please let me know if I should expand the code example. 开发者_如何学C
To create a new dictionary for each, you need to restate the keys:
entries_expanded[:] = [{'id':entry['id'], 'supplier':myfunction(entry['supplier'])} for entry in entries_expanded]
(If I've understood what you're trying to do correctly, anyway)
Isn't this what you want?
entries_expanded[:] = [
dict((entry['id'], myfunction(entry['supplier'])))
for entry in entries_expanded
]
You could think of it as a generator that creates tuples followed by a list comprehension that makes dictionaries:
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]
Alternatively, it is as the other answer suggests:
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
]
精彩评论