如何解决从字符串创建字典的问题
我有以下字符串。我正在将其转换为字典,但检索到的输出不是预期的输出。
result = ' Thomas got 99 and James got 95,Gerrard got 84 and Tim got 21'
mydict = dict((k.strip(),v.strip()) for k,v in
(item.split('and') for item in result.split(',')))
print(mydict)
output is: {'Thomas got 99': 'James got 95','Gerrard got 84': 'Tim got 21'}
我希望预期的输出如下所示
output is:{'Thomas': '99','James': '95','Gerrard': '84','Tim': '21'}
谢谢
解决方法
使用正则表达式。
例如:
import re
result = ' Thomas got 99 and James got 95,Gerrard got 84 and Tim got 21'
print(dict(re.findall(r"(\w+) got (\d+)",result)))
输出:
{'Thomas': '99','James': '95','Gerrard': '84','Tim': '21'}
,
尝试更改,而不是得到,并且没有那么多的“与”只是使用逗号而已
result = ' Thomas got 99,James got 95,Gerrard got 84,Tim got 21'
mydict = dict((k.strip(),v.strip()) for k,v in
(item.split('got') for item in result.split(',')))
print(mydict)
在我的IDE中运行此命令,结果就是您想要的,希望对您有帮助
,使用zip()函数创建两个列表的字典
import re
result = ' Thomas got 99 and James got 95,Gerrard got 84 and Tim got 21'
key = re.findall('[A-Z]+[a-z]+',result)
value = re.findall(r'\d+',result)
print(dict(zip(key,value)))
#{'Thomas': '99','Tim': '21'}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。