根据匹配的两个键创建新列表

时间:2019-03-07 16:28:28

标签: python

给定以x个字典为元素的y列表,我想产生一个新列表,其中包含一组连接的字典。每个字典都保证有一个名为“ homeworld”的键和一个名为“ name”的键,但除此之外可以有任意键集。例如,想象以下两个列表:

list1 = [{"name": "Leia Organa", "homeworld": "https://swapi.co/api/planets/2/"}, 
{"name": "C-3PO", "homeworld": "https://swapi.co/api/planets/1/"}, 
{"name": "Bail Prestor Organa", "homeworld": "https://swapi.co/api/planets/2/"}, 
{"name": "Luke Skywalker", "homeworld": "https://swapi.co/api/planets/1/"}]

list2 = [{"name": "Alderaan", "url": "https://swapi.co/api/planets/2/"},
{"name": "Yavin IV", "url": "https://swapi.co/api/planets/3/"}, 
{"name": "Tatooine", "url": "https://swapi.co/api/planets/1/"}]

基于键list1 ['homeworld']和list2 ['url'], 我想生成一个加入列表:

list3 = [
{"name": "Alderaan", "persons": ["Leia Organa", "Bail Prestor Organa"]},
{"name": "Tatooine", "persons": ["Luke Skywalker", "C-3PO"]}
]

在Python中执行此操作的最佳方法是什么?

到目前为止我尝试过的...

from collections import defaultdict

l1 = get_planets()['results']
l2 = get_people()['results']

d = defaultdict(dict)
for l in (l1, l2):           <-----is this even set up correctly?
    for elem in l:
        # how to write this here? if l2['homeworld'] == l1['url']: ???
            d[elem['name']].update(elem)  <---not sure what goes here
l3 = d.values()

1 个答案:

答案 0 :(得分:1)

您可以使用列表理解:

list1 = [{"name": "Leia Organa", "homeworld": "https://swapi.co/api/planets/2/"}, 
         {"name": "C-3PO", "homeworld": "https://swapi.co/api/planets/1/"}, 
         {"name": "Bail Prestor Organa", "homeworld": "https://swapi.co/api/planets/2/"}, 
         {"name": "Luke Skywalker", "homeworld": "https://swapi.co/api/planets/1/"}]

list2 = [{"name": "Alderaan", "url": "https://swapi.co/api/planets/2/"},
         {"name": "Yavin IV", "url": "https://swapi.co/api/planets/3/"}, 
         {"name": "Tatooine", "url": "https://swapi.co/api/planets/1/"}]

list3 = [{'name': x['name'], 'persons': [y['name'] for y in list1 if y['homeworld'] == x['url']]} for x in list2]

list3 = [x for x in list3 if x['persons']]

print(list3)
# [{'name': 'Alderaan', 'persons': ['Leia Organa', 'Bail Prestor Organa']}, 
#  {'name': 'Tatooine', 'persons': ['C-3PO', 'Luke Skywalker']}]