Python 从字符串创建字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4627981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a dictionary from a string
提问by user225312
I have a string in the form of:
我有以下形式的字符串:
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?
我知道我可以拆分,但我无法获得有关如何拆分的正确语法。如果我分裂-,那么我如何加入这两个部分?
Iterating over this seems to much of a pain.
迭代这个似乎很痛苦。
采纳答案by user225312
>>> 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'}
EDIT: 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}
回答by Jochen Ritzel
To solve your example you can do this:
要解决您的示例,您可以执行以下操作:
mydict = dict((k.strip(), v.strip()) for k,v in
(item.split('-') for item in s.split(',')))
It does 3 things:
它做了 3 件事:
- split the string into
"<key> - <value>"parts:s.split(',') - split each part into
"<key> ", " <value>"pairs:item.split('-') - remove the whitespace from each pair:
(k.strip(), v.strip())
- 将字符串分成
"<key> - <value>"几部分:s.split(',') - 将每个部分分成
"<key> ", " <value>"对:item.split('-') - 从每对中删除空格:
(k.strip(), v.strip())
回答by phihag
>>> dict((k.strip(),int(v.strip())) for k,v in (p.split('-') for p in s.split(',')))
{'A': 13, 'B': 14, 'M': 99, 'C': 29}
回答by Gerrat
dict((p.split(' - ') for p in s.split(',')))
回答by rubik
This should work:
这应该有效:
dict(map(lambda l:map(lambda j:j.strip(),l), map(lambda i: i.split('-'), s.split(','))))
If you don't want to strip, just do:
如果您不想剥离,请执行以下操作:
dict(map(lambda i: i.split('-'), s.split(',')))
回答by Steven Rumbalski
Here's an answer that doesn't use generator expressions and uses replacerather than strip.
这是一个不使用生成器表达式并使用replace而不是strip.
>>> s = 'A - 13, B - 14, C - 29, M - 99'
>>> d = {}
>>> for pair in s.replace(' ','').split(','):
... k, v = pair.split('-')
... d[k] = int(v)
...
>>> d
{'A': 13, 'C': 29, 'B': 14, 'M': 99}
回答by ??????? ????
Those who came here with following problem :
那些带着以下问题来到这里的人:
convert string a = '{"a":1,"b":2}'to dictionary object.
将字符串转换a = '{"a":1,"b":2}'为字典对象。
you can simply use a = eval(a)to get aas object of dictionary from a string object.
您可以简单地使用从字符串对象中a = eval(a)获取a字典对象。

