Reputation: 629
I have a dictionary data
, which has a keymessage
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?
Upvotes: 0
Views: 91
Reputation: 604
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'}}
Upvotes: 1
Reputation: 1505
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)
Upvotes: 1
Reputation: 880
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:])
Upvotes: 1