[英]pythonic way of parsing a string into a dictionary with dict comprehension
For a given string对于给定的字符串
key = "test: abc :bcd,ef:1923:g, x : y : z\nkey2 :1st:second\n etc :values:2,3,4:..."
I would like to parse the string to store into a dict with the first token as key and the rest elements as a value list, something like the following result:我想解析字符串以将第一个标记作为键存储到字典中,并将 rest 元素作为值列表,类似于以下结果:
{'test': ['abc', 'bcd,ef', '1923', 'g, x', 'y', 'z'], 'key2': ['1st', 'second'], 'etc': ['values', '2,3,4', '...']}
I have我有
def parseLine(line):
return list(map(str.strip, line.split(":")))
result = {parseLine(line)[0]:parseLine(line)[1:] for line in str_txt.split('\n')}
print(result)
But in the expression of the dict comprehensions, the function parseLine is invoked twice to set key and value for the dict as parseLine(line)[0]:parseLine(line)[1:]
.但是在 dict 理解的表达式中,调用 function parseLine 两次以将 dict 的键和值设置为
parseLine(line)[0]:parseLine(line)[1:]
。
Is there a better way to re-write the dict comprehensions?有没有更好的方法来重写 dict 理解?
{lst[0]:lst[1:] for lst in map(lambda s: list(map(str.strip, s.split(":"))), key.split('\n'))}
It gives:它给:
{'test': ['abc', 'bcd,ef', '1923', 'g, x', 'y', 'z'],
'key2': ['1st', 'second'],
'etc': ['values', '2,3,4', '...']}
You can use map
inside the comprehension to apply the function, and then destructure the results.您可以在推导式中使用
map
来应用 function,然后对结果进行解构。
result = {k: v for k, *v in map(parseLine, str_txt.split('\n'))}
Note also that if you're using parseLine
only for this, you can rewrite it without the conversion to list
:另请注意,如果您仅为此使用
parseLine
,则可以在不转换为list
的情况下对其进行重写:
def parseLine(line):
return map(str.strip, line.split(":"))
import re
s = "test: abc :bcd,ef:1923:g, x : y : z\nkey2 :1st:second\n etc :values:2,3,4:..."
s = re.sub(r'[^a-z0-9,]',' ',s)
print ({ x.split()[0]:x.split()[1:] for x in s.split("\n") })
Output: Output:
{'test': ['abc', 'bcd,ef', '1923', 'g,', 'x', 'y', 'z'], 'key2': ['1st', 'second'], 'etc': ['values', '2,3,4']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.