python基于条件匹配将文本行转换为字典



我有下面的字符串,需要帮助了解如何在for循环中编写if条件,该循环检查行.startswith('name'(是否取值并存储在名为name的变量中。多臂也是如此。

一旦for循环完成,输出应该是一个字典,如下所示,我可以将其转换为pandas数据帧。

'name johnn nnDOBn12/08/1984nncurrent companyngooglen'

这是我迄今为止尝试过的,但不知道如何将值放入字典

for row in lines.split('n'):
if row.startswith('name'):
name = row.split()[-1]

最终输出

data = {"name":"john", "dob": "12/08/1984"}

尝试使用列表理解和split:

s = '''name
john
dob
12/08/1984
current company
google'''
d = dict([i.splitlines() for i in s.split('nn')])
print(d)

输出:

{'name': 'john', 'dob': '12/08/1984', 'current company': 'google'}

最新更新