Here is my code:
# library to extract cookies in a http message
cj = cookielib.CookieJar()
... do connect to httpserver etc
cdict = ((c.name,c.value) for c in cj)
The problem with this code is cdict is a generator. But I want to simply create a dictionary. How can I change the last line to assign to a dictionary?
Use a dictionary comprehension. (Introduced in Python 2.7)
cdict = {c.name:c.value for c in cj}
For example,
>>> {i:i*2 for i in range(10)}
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Here is the PEP which introduced Dictionary Comprehensions. It may be useful.
If you are on something below Python 2.7. - Build a list of key value pairs and call dict()
on them, something like this.
>>> keyValList = [(i, i*2) for i in range(10)]
>>> keyValList
[(0, 0), (1, 2), (2, 4), (3, 6), (4, 8), (5, 10), (6, 12), (7, 14), (8, 16), (9, 18)]
>>> dict(keyValList)
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
OR Just pass your generator to the dict()
method. Something like this
>>> dict((i, i*2) for i in range(10))
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Use dict comprehension: {c.name:c.value for c in cj}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With