将带有2层定界符的字符串转换为字典-python [英] Convert a string with 2-tier delimiters into a dictionary - python

查看:47
本文介绍了将带有2层定界符的字符串转换为字典-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个字符串:

s = 'x\t1\ny\t2\nz\t3'

我想转换成字典:

sdic = {'x':'1','y':'2','z':'3'}

我通过执行以下操作使它起作用:

I got it to work by doing this:

sdic = dict([tuple(j.split("\t")) for j in [i for i in s.split('\n')]])

第一位:['x\t1','y\t2','z\t3'] # str.split('\n')

然后:[('x','1'),('y','2'),('z','3')] # tuples([str.split('\t')])

最后:{'x':'1', 'y':'2', 'z':'3'} # dict([tuples])

但是有没有更简单的方法可以将带有2层定界符的字符串转换为字典?

推荐答案

您在遍历列表理解时有点冗长:

You're a little verbose in your walking through list comprehensions:

>>> s = 'x\t1\ny\t2\nz\t3'
>>> dd = dict(ss.split('\t') for ss in s.split('\n'))
>>> dd
{'x': '1', 'y': '2', 'z': '3'}
>>>

这篇关于将带有2层定界符的字符串转换为字典-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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