将冒号分隔的列表转换成字典? [英] Converting colon separated list into a dict?

查看:399
本文介绍了将冒号分隔的列表转换成字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了类似的东西,将逗号分隔的列表转换成字典.

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

没有办法

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

还是什么?

推荐答案

如果我正确理解了您的要求,那么您可以使用以下一种语言.

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

示例:

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

您可能希望在拆分后strip()键和值以修剪空白.

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

这篇关于将冒号分隔的列表转换成字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆