使用列表推导将字符串转换为dict [英] convert string to dict using list comprehension

查看:59
本文介绍了使用列表推导将字符串转换为dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几次遇到这个问题,似乎无法找出一个简单的解决方案. 说我有一个字符串

I have came across this problem a few times and can't seem to figure out a simple solution. Say I have a string

string = "a=0 b=1 c=3"

我想将其转换为字典,其中a,b和c为键,0、1、3分别为值(转换为int).显然我可以做到这一点:

I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:

list = string.split()
dic = {}
for entry in list:
    key, val = entry.split('=')
    dic[key] = int(val)

但是我不太喜欢for循环,它看起来是如此简单,您应该可以将其转换为某种列表理解表达式.这适用于val可以是字符串的较简单情况.

But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the val can be a string.

dic = dict([entry.split('=') for entry in list])

但是,我需要即时将val转换为int,并且这样做在语法上是不正确的.

However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect.

dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list])

所以我的问题是:有没有一种方法可以使用列表理解来消除for循环?如果没有,是否有一些内置的python方法可以为我做到这一点?

So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?

推荐答案

您是这个意思吗?

>>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
{'a': 0, 'c': 3, 'b': 1}

这篇关于使用列表推导将字符串转换为dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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