在Python中使用以空格分隔的key = value字符串创建字典 [英] Creating dictionary from space separated key=value string in Python

查看:396
本文介绍了在Python中使用以空格分隔的key = value字符串创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串如下:

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'

我要转换成以下字典:


key  | value
-----|--------  
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace

如何在Python中做到这一点?

How do I do this in Python?

推荐答案

尝试一下:

>>> import re
>>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s))
{'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'}

如果您还想删除引号:

>>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}

这篇关于在Python中使用以空格分隔的key = value字符串创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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