给定以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()
您可以使用列表理解:
相关问题 更多 >
编程相关推荐