Home > database >  Convert list of dictionaries with different keys to values string list
Convert list of dictionaries with different keys to values string list

Time:08-27

Example list of dicts:

[{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]

Expected out = ['aly', '104', 'Not A name', '99']

Any help will be much appreciated.

Thanks!

CodePudding user response:

Try this in one line:

d = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]

[v for i in d for k,v in i.items()]

The result will be:

Out[1]: ['aly', '104', 'Not A name', '99']

CodePudding user response:

You can iterate over list and get dict and use dict.values() and use list.extend and insert values in expected_list.

lst_dct = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}] 
res = []
for dct in lst_dct:
    res.extend(dct.values())
print(res)

['aly', '104', 'Not A name', '99']

As an alternative, We can use functools.reduce.

from functools import reduce

res = reduce(lambda res, dct: res   list(dct.values()), lst_dct, [])

print(res)
# ['aly', '104', 'Not A name', '99']

CodePudding user response:

Another way :

listDictionary = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]
out = []
for i in listDictionary:
    for k, v in i.items():
        out.append(v)
print(out)

Output : ['aly', '104', 'Not A name', '99']

  • Related