Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert generator object to a dictionary

Tags:

python

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?

like image 952
Angus Comber Avatar asked Jul 23 '13 16:07

Angus Comber


2 Answers

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}
like image 171
Sukrit Kalra Avatar answered Sep 22 '22 12:09

Sukrit Kalra


Use dict comprehension: {c.name:c.value for c in cj}

like image 27
zhangyangyu Avatar answered Sep 25 '22 12:09

zhangyangyu