Nick
Nick

Reputation: 81

How to extract a list of values nested in a list of dict?

Here's an example code:

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'and', 'Bartholomew' 'Shoe'],
         {'name': 'Wisteria Ravenclaw', 'parents': ['Douglas', 'Lyphe', 'and', 'Jackson', 'Pot']
        }]

I need to get the parent's values and print them out as strings. An example output:

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

I tried:

list2 = []

 for i in list1:
    if i['parents']:
         list2.append(i['parents'])

then, I tried to join() them, but they are lists nested in a list so, I haven't got to the solution that I'm looking for yet.

Could someone help me figure this out, please?

Upvotes: 1

Views: 54

Answers (2)

glhr
glhr

Reputation: 4537

Using a list comprehension and join():

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'and', 'Bartholomew', 'Shoe']},
         {'name': 'Wisteria Ravenclaw', 'parents': ['Douglas', 'Lyphe', 'and', 'Jackson', 'Pot']}]

parents = ', '.join([' '.join(dic['parents']) for dic in list1])
print(parents)

Output:

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

The inner join() combines the elements in each names list (eg. ['John Doe', 'and', 'Bartholomew', 'Shoe'] becomes John Doe and Bartholomew Shoe), and the outer join() combines the two elements resulting from the list comprehension: John Doe and Bartholomew Shoe and Douglas Lyphe and Jackson Pot.

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You need to first join all words in the dictionary, append all those strings to a list, and then join the final list

list1 = [{'name': 'foobar', 'parents': ['John Doe', 'and', 'Bartholomew', 'Shoe']},
         {'name': 'Wisteria Ravenclaw', 'parents': ['Douglas', 'Lyphe', 'and', 'Jackson', 'Pot']
        }]

sentences = []
#Iterate over the list and join each parents sublist, and append to another list
for item in list1:
    sentences.append(' '.join(item['parents']))

#Join the final list
print(', '.join(sentences))

The output will be

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

Or just use list-comprehension

parents = ', '.join([' '.join(item['parents']) for item in list1])
print(parents)

Upvotes: 0

Related Questions