Reputation: 347
I am using Python 3.4, and I am testing out dictionary comprehension.
Let's say I have the following code:
listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}]
titles1 = []
titles2 = []
titles1.append({r["section"]: r["title"] for r in listofdict})
print("titles1 = " + str(titles1))
for r in listofdict:
section = r["section"]
title = r["title"]
titles2.append({section: title})
print("titles2 = " + str(titles2))
I thought both methods should give me the same result, but I get the following instead:
titles1 = [{'456': 'ewr', '123': 'asc'}]
titles2 = [{'123': 'asc'}, {'456': 'ewr'}]
titles2 is what I actually want, but I want to use dictionary comprehension to do it.
What is the right way to write the dictionary comprehension?
Upvotes: 1
Views: 339
Reputation: 1123400
You cannot use a dict comprehension for that, because a dict comprehension produces one dictionary with the keys and values taken from the loop(s).
You'd use a list comprehension instead:
[{r["section"]: r["title"]} for r in listofdict]
This produces the one dictionary each iteration, producing a new list:
>>> listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}]
>>> [{r["section"]: r["title"]} for r in listofdict]
[{'123': 'asc'}, {'456': 'ewr'}]
Upvotes: 8