格式和内联循环 Python 2.6

Format and inline loop Python 2.6

我有一个功能,需要 python 2.6 符合:

def find(entity, **kwargs):
    return instance.search(
        set(),
        {'search': '{0}="{1}"'.format(key, kwargs[key]) for key in kwargs}
    )

然而,python 2.6 完整性检查在字符位置 59 处失败,这是循环中的 "for"。 python 2.6 中的内联循环不正常吗?

词典理解在 Python 2.7 中引入。参见 PEP 274 -- Dict Comprehensions

您可以通过在键和值的生成器表达式上调用 dict 来构建字典:

def find(entity, **kwargs):
    return instance.search(
        set(),
        dict(('search', '{0}="{1}"'.format(key, kwargs[key])) for key in kwargs)
    )

但是请注意,您的字典将只包含一个键和一个值,因为 search 是您提供的唯一键,并且它不会在整个 gen 中发生变化。 exp.