将带有括号的字符串转换成字典 [英] Turning string with embedded brackets into a dictionary

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

问题描述

从像下面这样的字符串构建字典的最佳方法是什么:

What's the best way to build a dictionary from a string like the one below:

"{key1 value1} {key2 value2} {key3 {value with spaces}}"

所以键始终是没有空格的字符串,但是值是字符串还是大括号中的字符串(有空格)?

So the key is always a string with no spaces but the value is either a string or a string in curly brackets (it has spaces)?

您如何将其定义为:

{'key1': 'value1',   'key2': 'value2',   'key3': 'value with spaces'}

推荐答案

import re
x="{key1 value1} {key2 value2} {key3 {value with spaces}}"
print dict(re.findall(r"\{(\S+)\s+\{*(.*?)\}+",x))

您可以尝试一下.

输出:

{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}

在这里使用 re.findall 提取 key 及其 value . re.findall 返回带有以下内容的列表所有键,值对的元组.使用元组列表上的 dict 提供最终答案.在此处了解更多信息.

Here with re.findall we extract key and its value.re.findall returns a list with tuples of all key,value pairs.Using dict on list of tuples provides the final answer. Read more here.

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

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