首页 > 解决方案 > 如何提取嵌套在dict列表中的值列表?

问题描述

这是一个示例代码:

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

然后,我尝试加入()它们,但它们是嵌套在列表中的列表,所以我还没有找到我正在寻找的解决方案。

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

标签: python

解决方案


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


推荐阅读