Difference between Python dictionary comprehension and loop -
i using python 3.4, , testing out dictionary comprehension.
let's have following code:
listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}] titles1 = [] titles2 = [] titles1.append({r["section"]: r["title"] r in listofdict}) print("titles1 = " + str(titles1)) r in listofdict: section = r["section"] title = r["title"] titles2.append({section: title}) print("titles2 = " + str(titles2))
i thought both methods should give me same result, following instead:
titles1 = [{'456': 'ewr', '123': 'asc'}] titles2 = [{'123': 'asc'}, {'456': 'ewr'}]
titles2 want, want use dictionary comprehension it.
what right way write dictionary comprehension?
you cannot use dict comprehension that, because dict comprehension produces one dictionary keys , values taken loop(s).
you'd use list comprehension instead:
[{r["section"]: r["title"]} r in listofdict]
this produces 1 dictionary each iteration, producing new list:
>>> listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}] >>> [{r["section"]: r["title"]} r in listofdict] [{'123': 'asc'}, {'456': 'ewr'}]
Comments
Post a Comment