社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python中将字符串转换为dict

netbbq • 7 年前 • 2078 次点击  

我正在尝试用python将下面类型的字符串转换成字典。

'F1=Value1,F2=Value2,F3=[[F4=Value4,F5=Value5]],F6=Value6'

我想把字典做成:

{
    'F1': 'Value1', 
    'F2': 'Value2',
    'F3': '[[F4=Value4,F5=Value5]]',
    'F6': 'Value6'
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41185
文章 [ 1 ]  |  最新文章 7 年前
kcorlidy
Reply   •   1 楼
kcorlidy    8 年前

如果继续使用相同的字符串格式,则可以使用复杂的正则表达式来覆盖各种模式。

下面是一些模式的正则表达式。如果这能解决你的问题,请告诉我。如果没有,请提供我的解决方案失败的详细信息:

编辑解释

  1. 第一组 (?=F\d+=\[).*?(\]){2,}(?=|,)
    • (?=F\d+=\[) 匹配字符串以f开头,有一个或多个数字,并且 =[ 在他们之后
    • .*?(\]){2,} 尽可能少地匹配字符串,它有2个或更多 ] 最后
    • (?=|,) 弦的末端 , 或者什么都没有
  2. 第二组 F\d.[^,]+
    • 匹配第一组后,很容易找到类似 F6=Value6 . 因为第一组优先于第二组,所以第二组只能匹配其余的字符串。

代码

string = "F1=Value1,F2=Value2,F3=[[F4=Value4,F5=Value5]],F6=Value6,F7=[[[BC],[AC]]]"
import re
resultset = [ele[0] if ele[0] else ele[-1] for ele in re.findall(r"((?=F\d+=\[).*?(\]){2,}(?=|,))|(F\d.[^,]+)",string)]
print({x[:x.find("=")]:x[x.find("=")+1:] for x in resultset})

产量

{'F6': 'Value6', 'F2': 'Value2', 'F3': '[[F4=Value4,F5=Value5]]', 'F1': 'Value1', 'F7': '[[[BC],[AC]]]'}

编辑:因为前一个regex在string为 F1=Value1,F2=Value2,F8=[iD=10,ig=12S],F3=[[F4=Value4,F5=Value5]],F6=Value6,F9=[iD=10,ig=12S],F7=[[[BC],[AC]]]

我把regex改成 ((?=F\d+=\[).*?(\])+(?= |,F))|(F\d.[^,]+) . 我们需要一个技巧。 在字符串后添加一个空格 。

string = "F1=Value1,F2=Value2,F8=[iD=10,ig=12S],F3=[[F4=Value4,F5=Value5]],F6=Value6,F9=[iD=10,ig=12S],F7=[[[BC],[AC]]]"
import re
resultset = [ele[0] if ele[0] else ele[-1] for ele in re.findall(r"((?=F\d+=\[).*?(\])+(?= |,F))|(F\d.[^,]+)",string+" ")]
print({x[:x.find("=")]:x[x.find("=")+1:] for x in resultset})