'Trying to get column data from an a list of dictionaries
I have the following data:
locations = [
{"id": 1,"Name": "Ottawa"},
{"id": 2,"Name": "Ahmedabad"},
{"id": 3,"Name": "London"}
and I am trying to get an output which shows a list of names so: [Ottawa, Ahmedabad, London] or something similar to this.
How can I go about making this or is this even possible?
I have created a function that can give individual names
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}")
that gives an output of "Ottawa" when looking at that specific route.
Solution 1:[1]
Your function filters for some Name. Remove that and it should work
# use a list comprehension
[d['Name'] for d in locations]
# ['Ottawa', 'Ahmedabad', 'London']
Another way is to call operator.itemgetter
from operator import itemgetter
print(*map(itemgetter('Name'), locations))
# Ottawa Ahmedabad London
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | not a robot |
