[英]need help in making key value pair in python
I have this code: 我有以下代码:
while i<len(line):
if re.findall(pattern, line[i]):
k,v = line[i].split('=')
print k
token = dict(k=v)
print token
break
and the result I'm getting is : 我得到的结果是:
ptk
{'k': 'ptk_first'}
how to make this few lines of code nicer and dictionary that will look like this: 如何使这几行代码更好看并像下面这样的字典:
{'ptk': 'ptk_first'}
for line in lines:
if re.match(pattern, line):
k,v = line.split('=')
token = {k:v}
print token
Something like this: 像这样:
lines="""\
key1=data on the rest of line 1
key2=data on the rest of line 2
key3=data on line 3"""
d={}
for line in lines.splitlines():
k,v=line.split('=')
d[k]=v
print d
In [112]: line="ptk=ptk_first"
In [113]: dict([line.split("=")])
Out[113]: {'ptk': 'ptk_first'}
for your code: 为您的代码:
for line in lines:
if re.findall(pattern, line):
token = dict([line.split("=")])
print token
with regex you can try this: 使用正则表达式,您可以尝试以下操作:
>>> import re
>>> lines="""
... ptk=ptk_first
... ptk1=ptk_second
... """
>>> dict(re.findall('(\w+)=(\w+)',lines,re.M))
{'ptk1': 'ptk_second', 'ptk': 'ptk_first'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.