繁体   English   中英

Python - 将字符串拆分为字典

[英]Python - split string into dictionary

我的情况如下。 我有一个像这样的刺痛“清单”

Text1
Text2: value1
Text3:
Text4:
Text5: value2
...

现在我想将文本拆分为带有键值对的字典。

我用这个 1liner 试过了

sp = dict(s.split(':') for s in list.split('\n') if len(s) > 1 and s.count(':') > 0)

这很好用,直到没有像 Text3 和 Text4 那样的值。

我的最终字典应该是这样的

{ Text2:value1,Text3:'',Text4:'',Text5:value2 }

Text1 应该被跳过 - 但 Text3 & Text4 我需要在字典中,如果值为空。

对于您的情况Key:http:// xyz .com您必须在第一场比赛后使用s.split(':', 1))停止拆分

my_str = """Text1
Text2: value1
Text3:
Text4:
Text5: value2
Key:http:// xyz .com 
"""

sp = dict(map(str.strip, s.split(':', 1)) for s in my_str.split('\n') if ':' in s)
print(sp)

输出:

{'Text2': 'value1', 'Text3': '', 'Text4': '', 'Text5': 'value2', 'Key': 'http:// xyz .com'}

由于这个问题,我只能在评论的帮助下发现,我可以通过这种方式解决问题

my_str = """Text1
Text2: value1
Text3:
Text4:
Text5: value2
Text6:http: // something
"""

问题是,由于值字段中的网络地址,最后一行被分成 3 部分。

sp = dict(s.split(':') for s in my_str.split('\n') if len(s) > 1 and s.count(':') == 1)

也许有更好的方法,但我检查了拆分字符“:”是否只出现 1 次 - 因为那样我肯定会得到一对,我可以插入字典:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM