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
284 views
in Technique[技术] by (71.8m points)

python - Converting colon separated list into a dict?

I wrote something like this to convert comma separated list to a dict.

def list_to_dict( rlist ) :
    rdict = {}
    i = len (rlist)
    while i:
        i = i - 1
        try :
            rdict[rlist[i].split(":")[0].strip()] = rlist[i].split(":")[1].strip()
        except :
            print rlist[i] + ' Not a key value pair'
            continue


    return rdict

Isn't there a way to

for i, row = enumerate rlist
    rdict = tuple ( row ) 

or something?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If I understand your requirements correctly, then you can use the following one-liner.

def list_to_dict(rlist):
    return dict(map(lambda s : s.split(':'), rlist))

Example:

>>> list_to_dict(['alpha:1', 'beta:2', 'gamma:3'])
{'alpha': '1', 'beta': '2', 'gamma': '3'}

You might want to strip() the keys and values after splitting in order to trim white-space.

return dict(map(lambda s : map(str.strip, s.split(':')), rlist))

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

...