XXXXXX
XXXXXX

Reputation: 21

How can I call a entries in a dictionary when it is in a list?

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.

Upvotes: 0

Views: 43

Answers (3)

Yaman Jain
Yaman Jain

Reputation: 1251

Another approach is using itemgetter from the 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))

Upvotes: 1

Alibederchi
Alibederchi

Reputation: 19

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)

Upvotes: 0

charon25
charon25

Reputation: 316

You can do it with a list comprehension like:

print([lst["name"] for lst in list_names])

Upvotes: 2

Related Questions