1

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.

2
  • Which version of Python are you using? Commented Nov 11, 2010 at 20:31
  • Could you provide a sample of input data as well as what you expect the output to look like? Commented Nov 11, 2010 at 20:33

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

3

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
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.