Python 字典理解

Python Dict Comprehension

这感觉应该很明显,但我缺少正确的形式。

给定一个字符串列表,例如

fields = ["format = gatheringnutsinmay", "device = TESTX"]

我正在尝试编写字典理解来制作字段字典:

items = {"format": "gatheringnutsinmay", "device": "TESTX }

我现在有:

_kv_seperator = re.compile(r"\s*=\s*")
items = {fk: fv for f in fields for [fk, fv] in _kv_seperator.split(f)}

但我收到错误消息:

_kv_seperator.split(f)

ValueError: too many values to unpack (expected 2)

请指正!

如果格式固定,建议使用.split():

fields = ["format = gatheringnutsinmay", "device = TESTX"]
result = {}
for f in fields:
    f = f.split(" = ")
    result[f[0]] = f[1]
print(result)

您不需要第二个 for 循环,查看字典理解的一种方法如下:

items = {}
for f in fields:
    for [fk, fv] in _kv_seperator.split(f):
        items[fk] = fv

print(items)

当你写:

for [fk, fv] in _kv_seperator.split(f)

你告诉 Python 你期待一个由 2 元组组成的可迭代对象,但实际上

_kv_seperator.split(f) 

只有 returns 一个元组,因此错误:

ValueError: too many values to unpack (expected 2)

您可以改为执行以下操作:

import re

fields = ["format = gatheringnutsinmay", "device = TESTX"]
_kv_seperator = re.compile(r"\s*=\s*")
items = {fk: fv for fk, fv in map(_kv_seperator.split, fields)}

print(items)

或者简单地说:

items = dict(map(_kv_seperator.split, fields))
print(items)

或者,如果您愿意,您可以这样做:

items = {fk: fv for fk, fv in (_kv_seperator.split(f) for f in fields)}
items = { i.split('=')[0]:i.split('=')[1] for i in fields}

如果你想要一个衬垫,这就可以了:

items = {k:v for k,v in (sp.split(' = ') for sp in fields)}

您可以使用下面的代码代替 rex :

fields = ["format = gatheringnutsinmay", "device = TESTX"]
items = {f.split(" = ")[0]: f.split(" = ")[1] for f in fields}
items

希望对您有所帮助。