Home > front end >  Convert string into array or list of dicts
Convert string into array or list of dicts

Time:05-25

I am running an API call that gives as output the next string:

"[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"

I want to access location what should I do in this case ?

I am thinking of converting the string into array of dictionaries or list of dictionaries?

CodePudding user response:

import ast

s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
lst = ast.literal_eval(s)
print(lst)
# [{'hour': '5', 'day': '11', 'month': 'sep', 'year': '2019'}, {'user_id': 'x651242w', 'session_id': 4025, 'location': 'USA'}]
print(lst[1]['location'])
# USA

CodePudding user response:

s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
res = list(eval(s))
print(res[1]["location"])
'USA'

CodePudding user response:

Let's assume that you don't know which of the dictionaries contains the location key. This might give you some more general ideas too:

from ast import literal_eval

s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"

for dict_ in literal_eval(s):
  if location := dict_.get('location'):
    print(location)

Output:

USA

CodePudding user response:

This looks json, for json , we have to change single quote to double quote and then you can parse the json:

str1 = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, 
         {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
json_str = str1.replace("'", '"')
json_format = json.loads(a)
json_format[1]["location"]

CodePudding user response:

Look at the json module to parse the string into a list of dicts.

  • Related