14

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?

4

5 回答 5

24

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}
于 2013-07-23T16:34:52.873 回答
1

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

于 2013-07-23T16:34:59.907 回答
1

You can use a dict comprehension:

cdict = {c.name: c.value for c in cj}
于 2013-07-23T16:35:06.863 回答
1

I would say that the easiest way is just using the dict() constructor. Here an example:

def create_dummy_generator():
for i in range(10):
    yield i, i*2
x = create_dummy_generator()
y = dict(x)
type(x)
# <class 'generator'>
print(x)
# <generator object create_generator at 0x7fde3c562f90>
type(y)
# <class 'dict'>
print(y)
# {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
于 2021-04-29T09:49:00.987 回答
0

You can use this:

cdict = {c.name:c.value for c in cj}
于 2013-07-23T16:35:42.007 回答