So basically I have this list in code
list_names = [
{"name":"Jullemyth","seat_number":4,"category":"Student"},
{"name":"Leonhard","seat_number":1,"category":"OFW"},
{"name":"Scarion","seat_number":3,"category":"Businessman"},
{"name":"Jaguar","seat_number":2,"category":"Animal Manager"},
{"name":"Cutiepie","seat_number":10,"category":"Streamer"},
{"name":"Hannah Bee","seat_number":11,"category":"Streamer"}
]
I was thinking I could print only all the names by this
print(list_names[:]["name"])
but it doesn't work...how can I do that? I just want to get all the list of names in dict. Is that possible or not? without using loops.
CodePudding user response:
You can do it with a list comprehension like :
print([lst["name"] for lst in list_names])
CodePudding user response:
You cannot iterate upon all items without looping through them , the shortest way is to use list comprehension ,
for name in [D['name'] for D in list_names]:
print(name)
CodePudding user response:
Another approach is using itemgetter
from operator
module
import operator
list_names = [
{"name":"Jullemyth","seat_number":4,"category":"Student"},
{"name":"Leonhard","seat_number":1,"category":"OFW"},
{"name":"Scarion","seat_number":3,"category":"Businessman"},
{"name":"Jaguar","seat_number":2,"category":"Animal Manager"},
{"name":"Cutiepie","seat_number":10,"category":"Streamer"},
{"name":"Hannah Bee","seat_number":11,"category":"Streamer"}
]
output_names = list(map(operator.itemgetter('name'), list_names))