简体   繁体   中英

extract nested dictonary from String data[PYTHON]

I have a dictionary data , which has a key message and value is 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

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

I don't want to use 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

>>> 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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