Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - Creating a dictionary from a string

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • 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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...