繁体   English   中英

从字符串数据中提取嵌套字典[PYTHON]

[英]extract nested dictonary from String data[PYTHON]

我有一个字典data ,它有一个关键message ,值为string

字典中的值是字符串+内部字典的组合。

我想提取内部字典作为单独的字典。

示例输入

data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}

Example_output

output = {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}

我不想使用 python SPLIT

任何人都可以为此提出解决方案吗?

您可以简单地搜索第一个{并使用索引来获取字典在字符串中的位置。

import ast

index_dict = data['message'].find('{')
output = ast.literal_eval(data['message'][index_dict:])

使用正则表达式:

import re
import ast

data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
output = {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}

message = re.findall(r'^\[INFO\]-processed-result - (.*)', data['message']).pop()
output = ast.literal_eval(message)
print(output)

使用str index方法并使用内置eval另一种方法

>>> data = {'message': '[INFO]-processed-result-2020-10-01T23:45:49.472Z- {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
>>> index = data['message'].index('{')
>>> output = eval(data['message'][index:])
>>> output
{'customer_id': 'cust_111', 'user_ids': [1, 2, 3], 'collection': {'default': 'def_1'}}
>>>
>>> data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
>>> index = data['message'].index('{')
>>> output = eval(data['message'][index:])
>>> output
{'customer_id': 'cust_111', 'user_ids': [1, 2, 3], 'collection': {'default': 'def_1'}}

您也可以考虑使用json.loads()以获得更快的解决方案

>>> import json
>>> json.loads(data['message'][index:])
{'customer_id': 'cust_111', 'user_ids': [1, 2, 3], 'collection': {'default': 'def_1'}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM