Search code examples
pythonjsonpython-3.xdictionarystring-parsing

Parse single qouted dictionary key and value in Python


I have a Python dictionary

original_dict={'body': '{"infra":["dev4","elk"],{"type":"file_integrity"}'}

I want to be able to parse original_dict keys and values as a normal dictionary which I am not able to do now because 'body' key has a a dictionary casted as string and therefore I am not refer to any of it's keys. So I should be able to say:

infra=original_dict['body]['infra']

Can anyone help me out with this.


Solution

  • First of all, you are missing a curly brace in the original_dict. Here is an example of converting a string into a dictionary.

        import json
        original_dict={'body':'{"infra":["dev4","elk"],"type":"file_integrity"}'}
        original_dict['body'] = json.loads(original_dict['body'])
        infra=original_dict['body']['infra']
        print(infra)
    

    Output : ['dev4', 'elk']