python - 将生成器对象转换为字典

标签 python

这是我的代码:

# 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)

这段代码的问题是 cdict 是一个生成器。但我只想创建一本字典。如何更改最后一行以分配给字典?

最佳答案

使用字典理解。 (在 Python 2.7 中引入)

cdict = {c.name:c.value for c in cj}

例如,

>>> {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}

这是 PEP其中引入了字典理解。它可能会有用。

如果您使用的是 Python 2.7 以下的版本。 - 构建一个键值对列表并对其调用 dict(),就像这样。

>>> 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 只需将您的生成器传递给 dict()方法。像这样

>>> 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}

关于python - 将生成器对象转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815945/

相关文章:

python - Tensorflow 实时对象检测 - 需要优化建议

python -/django.db.utils.IntegrityError : NOT NULL constraint failed/after python manage. py 迁移应用程序零

python - 为什么 `obj.method is obj._class__method` 是假的

python - 如何使用Python编写 "Hello World"RESTful API然后使用它

python - 使用nosetest时cfg文件中的插件出错

python - Powershell 输出为数组 (Python)

python - 计算 Pandas 系列中值的出现次数?

python - 使用 MATLAB 和 Python 范数函数得到不同的答案

python - 如何根据线性回归结果绘制S形曲线?

python - 导入最新 Pyside 版本时出现问题