如何将该语法转换为python 2.6

时间:2013-10-18 01:28:20

标签: python python-2.7 python-2.6

嗨我有一个非常快速的问题

for header in cookie_headers:
    pairs = [pair.partition("=") for pair in header.split(';')]
    cookie_name = pairs[0][0] # the key of the first key/value pairs
    cookie_value = pairs[0][2] # the value of the first key/value pairs
    cookie_parameters = {key.strip().lower():value.strip() for key,sep,value in pairs[1:]}
    cookies.append((cookie_name, (cookie_value, cookie_parameters)))
return dict(cookies)
我有一些类似的代码 cookie_parameters不适用于python 2.6 我安装了2.7,但它在python 2.6中需要的库我混淆了太多 只需要学习如何在2.6

中编写这种语法
    cookie_parameters = {key.strip().lower():value.strip() for key,sep,value in pairs[1:]}

2 个答案:

答案 0 :(得分:3)

cookie_parameters = dict((key.strip().lower(), value.strip())
                         for key,sep,value in pairs[1:])

更一般地说,任何字典理解都是这样的:

{<keyexpr>: <valueexpr> for <comprehension_target>}

......相当于:

dict((<keyexpr>, <valueexpr>) for <comprehension_target>)

...因为dict构造函数可以采用任何可迭代的(键,值)对。

当然,除了dict理解会更快,但在Python 2.7之前不能工作......

答案 1 :(得分:0)

自Python 2.7以来引入了Dict理解。请参阅:What’s New in Python 2.7

构建字典有三种方法:

class dict(**kwarg) e.g. dict(one=2, two=3)

class dict(mapping, **kwarg) e.g. dict({'one': 2, 'two': 3})
class dict(iterable, **kwarg) e.g. dict(zip(('one', 'two'), (2, 3))) Or dict([['two', 3], ['one', 2]])

列表推导和生成器是可迭代的,你可以将dict()与它们结合起来