如何提取嵌套在字典列表中的值列表?

时间:2019-05-04 12:39:15

标签: python

这是示例代码:

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

我需要获取父级的值并将其打印为字符串。输出示例:

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

我尝试过:

list2 = []

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

然后,我尝试了join()它们,但是它们是嵌套在列表中的列表,因此,我还没有找到想要的解决方案。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

使用列表理解和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)

输出:

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

内部join()组合每个名称列表中的元素(例如['John Doe', 'and', 'Bartholomew', 'Shoe']变成John Doe and Bartholomew Shoe),外部join()组合从列表理解中得到的两个元素:John Doe and Bartholomew ShoeDouglas Lyphe and Jackson Pot

答案 1 :(得分:0)

您需要首先将字典中的所有单词连接在一起,将所有这些字符串附加到列表中,然后再连接最终列表

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))

输出将为

John Doe and Bartholomew Shoe, Douglas Lyphe and Jackson Pot

或者只使用list-comprehension

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