本文介绍了从字符串创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串形式:
s = 'A - 13, B - 14, C - 29, M - 99'
等等(长度不同)。从这个最简单的方法来创建一个字典?
and so on (the length varies). What is the easiest way to create a dictionary from this?
A: 13, B: 14, C: 29 ...
我知道我可以拆分,但是我无法获得正确的语法。如果我在 -
上分裂,那么我如何加入这两个部分?
I know I can split but I can't get the right syntax on how to do it. If I split on -
, then how do I join the two parts?
迭代这似乎是痛苦
推荐答案
>>> s = 'A - 13, B - 14, C - 29, M - 99'
>>> dict(e.split(' - ') for e in s.split(','))
{'A': '13', 'C': '29', 'B': '14', 'M': '99'}
编辑:下一个解决方案是当你想要的值作为整数,我认为是你想要的。
The next solution is for when you want the values as integers, which I think is what you want.
>>> dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))
{'A': 13, ' B': 14, ' M': 99, ' C': 29}
这篇关于从字符串创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!