将字符串转换为字典的简单方法 [英] Simple way to convert a string to a dictionary

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

问题描述

将关键字=值的字符串转换为字典的最简单方法是什么,例如以下字符串:

What is the simplest way to convert a string of keyword=values to a dictionary, for example the following string:

name="John Smith", age=34, height=173.2, location="US", avatar=":,=)"

到以下python字典:

to the following python dictionary:

{'name':'John Smith', 'age':34, 'height':173.2, 'location':'US', 'avatar':':,=)'}

'avatar'键只是为了表明字符串可以包含=和,因此简单的'split'不会起作用.有任何想法吗?谢谢!

The 'avatar' key is just to show that the strings can contain = and , so a simple 'split' won't do. Any ideas? Thanks!

推荐答案

这对我有用:

# get all the items
matches = re.findall(r'\w+=".+?"', s) + re.findall(r'\w+=[\d.]+',s)

# partition each match at '='
matches = [m.group().split('=', 1) for m in matches]

# use results to make a dict
d = dict(matches)

这篇关于将字符串转换为字典的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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