在 Python 中将分号分隔的字符串拆分为字典 [英] Splitting a semicolon-separated string to a dictionary, in Python

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

问题描述

我有一个看起来像这样的字符串:

"Name1=Value1;Name2=Value2;Name3=Value3"

Python 中是否有一个内置的类/函数可以接受该字符串并构造一个字典,就好像我已经这样做了一样:

dict = {"名称 1": "值 1","Name2": "Value2",名称 3":值 3"}

我浏览了可用的模块,但似乎找不到任何匹配的内容.

<小时>

谢谢,我确实知道如何自己制作相关代码,但由于这些小解决方案通常是等待发生的雷区(即有人写道:Name1='Value1=2';)等,那么我通常更喜欢一些预先测试过的功能.

那我自己做.

解决方案

没有内置,但您可以使用生成器推导式相当简单地完成此操作:

s="Name1=Value1;Name2=Value2;Name3=Value3"dict(item.split("=") 用于 s.split(";"))

从您的更新中您表明您可能需要处理引用.这确实使事情复杂化,这取决于您要查找的确切格式是什么(接受什么引号字符,什么转义字符等).您可能想查看 csv 模块,看看它是否可以覆盖您的格式.这是一个示例:(请注意,此示例的 API 有点笨拙,因为 CSV 旨在遍历一系列记录,因此我进行的 .next() 调用只是为了查看第一行.调整为满足您的需求):

<预><代码>>>>s = "Name1='Value=2';Name2=Value2;Name3=Value3">>>dict(csv.reader([item], delimiter='=', quotechar="'").next()对于 csv.reader([s], delimiter=';', quotechar="'").next()) 中的项目{'名称2':'值2','名称3':'值3','名称1':'值1=2'}

不过,根据格式的确切结构,您可能需要编写自己的简单解析器.

I have a string that looks like this:

"Name1=Value1;Name2=Value2;Name3=Value3"

Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:

dict = {
    "Name1": "Value1",
    "Name2": "Value2",
    "Name3": "Value3"
}

I have looked through the modules available but can't seem to find anything that matches.


Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.

I'll do it myself then.

解决方案

There's no builtin, but you can accomplish this fairly simply with a generator comprehension:

s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))

[Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):

>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"

>>> dict(csv.reader([item], delimiter='=', quotechar="'").next() 
         for item in csv.reader([s], delimiter=';', quotechar="'").next())

{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}

Depending on the exact structure of your format, you may need to write your own simple parser however.

这篇关于在 Python 中将分号分隔的字符串拆分为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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