【问题标题】:Parse string representation of dictionary to dictionary将字典的字符串表示解析为字典
【发布时间】:2019-03-20 19:53:05
【问题描述】:

与这篇文章略有不同的用例: Convert a String representation of a Dictionary to a dictionary?

不同之处在于我从 Excel 电子表格中读取数据,因此我的字符串如下所示:

'{numerator: BV, denominator: Price}'

键或值周围没有引号。想知道是否有一些简单的方法可以将其转换为字典。我不认为 ast 的用法不起作用。

我已经这样做了,但我怀疑这是最好的方法。有什么建议吗?

test_params = '{numerator: BV, denominator: Price}'
comma_split = test_params.replace("{", "").replace("}", "").split(",")

reconstructed_params = {}

for i in comma_split:
    splitted = i.split(":")
    splitted[0] = splitted[0].strip()
    splitted[1] = splitted[1].strip()
    reconstructed_params[splitted[0]] = splitted[1]

print(reconstructed_params)

{'numerator': 'BV', 'denominator': 'Price'}

一个不错的简单方法会很棒。有时我的值是列表,但我想一次只做一件事。

【问题讨论】:

  • 如果它不符合任何类型的既定标准,那么极不可能有一种“简单”的方法来做到这一点。它必须和你一样。

标签: python-3.x string dictionary


【解决方案1】:

这里的引号是为了保护键和值免受其他引号、冒号、大括号等的影响。现在,如果键是值是字母数字,您可以应用正则表达式来添加引号,然后使用ast.literal_eval

import re,ast

d = ast.literal_eval(re.sub('(\w+)',r'"\1"','{numerator: BV, denominator: Price}'))

>>> type(d)
<class 'dict'>
>>> d
{'denominator': 'Price', 'numerator': 'BV'}

这个解决方案是相当通用的假设,因为它也可以解码嵌套字典。

【讨论】:

  • 这很好,解决了我的问题和其他用例。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多