将字符串化的词典列表转换回词典列表 [英] Convert stringified list of dictionaries back to a list of dictionaries

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

问题描述

我知道要使用字典将字符串转换为字符串,可以使用json.loadsjson.dumps.但是,当给定表示字典列表的字符串时,这些方法将失败.例如

I know that to convert a dictionary to/from a string, I use json.loads and json.dumps. However, those methods fail when given a string representing a list of dictionaries. For example,

sample_entry = [
    {"type": "test", "topic": "obama", "interval": "daily"},
    {"type": "test", "topic": "biden", "interval": "immediate"},
]

使用str()将其转换为字符串可以使我们

Converting that to a string with str() gives us

"[{'topic': 'obama', 'interval': 'daily', 'type': 'test'}, {'topic': 'biden', 'interval': 'immediate', 'type': 'test'}]"

是否有一种简单的方法可以将其转换回词典列表? eval确实可以满足我的要求,但是我担心要在用户提供的字符串上运行它.

Is there an easy way of converting this back to a list of dictionaries? eval does precisely what I want, but I'm concerned about running it on a user-supplied string.

还有另一种方法可以做到这一点,在面对可变的列表长度和可变的空白时会很健壮吗?

Is there another way of accomplishing this that will be robust in the face of varying list lengths and variable white space?

虽然json.loads(json.dumps(sample_entry))确实起作用,但json.loads(str(sample_entry))却无效.似乎区别在于使用单引号和双引号.我从中接收此字符串的数据源在使用"vs"时不太可能保持一致,因此我想将两者都考虑在内.

While json.loads(json.dumps(sample_entry)) does indeed work, json.loads(str(sample_entry)) does not. The difference, it seems, is where single quotes and double quotes are used. The data source I'm receiving this string from is unlikely to be consistent in use of ' vs ", so I'd like to account for both.

推荐答案

您可以使用

You may use ast.literal_eval:

>>> import ast
>>> my_str = "[{'topic': 'obama', 'interval': 'daily', 'type': 'test'}, {'topic': 'biden', 'interval': 'immediate', 'type': 'test'}]"

>>> ast.literal_eval(my_str)
[{'interval': 'daily', 'type': 'test', 'topic': 'obama'}, {'interval': 'immediate', 'type': 'test', 'topic': 'biden'}]

根据 ast.literal_eval文档,它:

As per the ast.literal_eval document, it:

安全地评估包含Python文字或容器显示的表达式节点或Unicode或Latin-1编码的字符串.提供的字符串或节点只能由以下Python文字结构组成:字符串,数字,元组,列表,字典,布尔值和无.

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

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

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