Home > OS >  Extract a value from a dictionary that is inside a list and a string in Python
Extract a value from a dictionary that is inside a list and a string in Python

Time:01-11

I don't seem to able to create a list from dictionary values are inside a list and a string in Python

string = "[{'iso_639_1': 'en', 'name': 'English'}, {'iso_639_1': 'ru', 'name': 'Pусский'}, {'iso_639_1': 'es', 'name': 'Español'}]"

desired_outcome = ['English', 'Pусский', 'Español']

CodePudding user response:

I generalized it, but here's what you are looking for I believe in Python. This is assuming that you always want the value associated with the "name" key for each of the dictionaries.

starting_dict = [{'key1': 'val1','name': 'val2'}, 
                 {'key3': 'val3','name': 'val4'}, 
                 {'key5':'val5','name': 'val6'}]
value_lst = list()
for my_dict in starting_dict:
  value_lst.append(my_dict['name'])
print(value_lst)

Output:

['val2', 'val4', 'val6']

CodePudding user response:

I would first format the string to JSON, then use json.loads to deserialize the string into a Python dictionary.

string = '[{"iso_639_1": "en", "name": "English"}, {"iso_639_1": "ru", "name": "Pусский"}, {"iso_639_1": "es", "name": "Español"}]'
dictionary = json.loads(string)

Then to collect a value from a list of dicts use a list comprehension:

names = [i['name'] for i in dictionary]
  •  Tags:  
  • Related