从字符串创建字典的问题

我有以下字符串。我正在将它转换为字典,但我检索的输出不是预期的输出。


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'}

谢谢


千巷猫影
浏览 130回答 3
3回答

繁花如伊

使用 zip() 函数从两个列表创建字典import reresult = ' 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', 'James': '95', 'Gerrard': '84', 'Tim': '21'}

蝴蝶不菲

使用正则表达式。前任:import reresult = ' 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 中运行这个,结果就是你要找的,希望这有帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python