Search code examples
pythondictionaryevalnested-loopsnested-lists

Iterate through list of dictionaries in Python and return value


I have a list of dictionaries in this format:

user_input =[{
    'user':'guest',
    'record':
    '{"message":"User Request","context":{"session_id":"YWOZe"},"level":100}'
},
{
    'user':'guest',
    'record':
    '{"message":"User Inquiry","context":{"session_id":"YWOZf"},"level":100}'
},
]

What I want is, I want to use eval in eval(user_input[0]['record']) and eval(user_input[1]['record']) by iterating over two dictionaries, so far I could do for one dictionary as

def record_to_objects(data:dict):
    new_dict = {}
    for key, value in data.items():
        if data[key] == data['record']:
            new_dict['record'] = eval(data['record'])
            r = data
            del r['record']
            return {**r, **new_dict} 

But for two dictionaries in a list, I got only one result(as the last item) using "double for loop", maybe I am not returning in a proper way. Expected output:

output = [
    
    {'user': 'guest',
     'record': {'message': 'User Request',
                'context': {'session_id': 'YWOZe'},
                'level': 100}},
    
    {'user': 'guest',
     'record': {'message': 'User Inquiry',
                'context': {'session_id': 'YWOZf'},
                'level': 100}}
]

Can somebody help me? I want a list of dictionaries and both should have been processed by the eval method.


Solution

  • That looks like JSON. You should not use eval() for this. Instead, use json.loads() with a for loop:

    import json
    
    for item in user_input:
        item["record"] = json.loads(item["record"])
    

    This outputs:

    [
     {
      'user': 'guest',
      'record': {'message': 'User Request', 'context': {'session_id': 'YWOZe'}, 'level': 100}
     },
     {
      'user': 'guest',
      'record': {'message': 'User Inquiry', 'context': {'session_id': 'YWOZf'}, 'level': 100}
     }
    ]