首页 > 解决方案 > 将文本转换为键值对

问题描述

给定这样的文本:

"$key\n
some value\n
$another_key\n
another longer\n
value\n"

# continue this trend with keys on lines marked by special symbol in this case $ 
# with corresponding value on the following lines until we hit another key

将它转换成这样的列表会有什么好的和简洁的方法

keys = ["$key", "$another_key"]
values = ["some value", "another longervalue"]

标签: python

解决方案


您可以在行首使用 $ 来识别这是一个新键,将其附加到键列表中,并将新的空白字符串附加到值列表中。然后,每次您有一行不以 $ 开头时,您将该值连接到值的最后一个元素,因为该行必须与当前键相关。只有当您读取一个新键时,您才会创建一个新的空白值元素。

data = "$key\nsome value\n$another_key\nanother longer\nvalue\n"
keys = []
values = []
for line in data.split('\n'):
    if line.startswith('$'):
        keys.append(line)
        values.append("")
    else:
        values[-1] += line
print(keys, values)

输出

['$key', '$another_key'] ['some value', 'another longervalue']

推荐阅读