我有以下数据:
locations = [
{"id": 1,"Name": "Ottawa"},
{"id": 2,"Name": "Ahmedabad"},
{"id": 3,"Name": "London"}
]
,我试图得到一个输出,其中显示的名称列表,所以:
[Ottawa, Ahmedabad, London]
或者类似的东西。我该怎么做,或者这有可能吗?
我已经创建了一个函数,可以给出单个名称
def find_names(Name):
try:
return ( location['Name'] for location in locations if location['Name'] == Name)
except:
raise BadRequest(f"Can't find the location by name {Name}")
,在查看特定路由时给出"Ottawa"
的输出。
您的函数筛选某些名称。删除它,它应该可以工作
# use a list comprehension
[d['Name'] for d in locations]
# ['Ottawa', 'Ahmedabad', 'London']
另一种方法是调用operator.itemgetter
from operator import itemgetter
print(*map(itemgetter('Name'), locations))
# Ottawa Ahmedabad London