[英]extract nested dictonary from String data[PYTHON]
I have a dictionary data
, which has a key message
and value is string
.我有一个字典data
,它有一个关键message
,值为string
。
the value in the dictionary is a combination of string + inner-dictionary.字典中的值是字符串+内部字典的组合。
I want to extract inner-dictionary as a separate dictionary.我想提取内部字典作为单独的字典。
Example-input示例输入
data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
Example_output Example_output
output = {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}
I don't want to use python SPLIT我不想使用 python SPLIT
Can anyone suggest solution for this?任何人都可以为此提出解决方案吗?
You can simply search for the first {
and use indexing to get the location of the dictionary within the string.您可以简单地搜索第一个{
并使用索引来获取字典在字符串中的位置。
import ast
index_dict = data['message'].find('{')
output = ast.literal_eval(data['message'][index_dict:])
Use Regular Expressions:使用正则表达式:
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)
Another way using index
method of str
and using inbuilt eval
使用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'}}
You can also consider using json.loads()
for a faster solution您也可以考虑使用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.