Skip to content
Advertisement

Defining two objects at once using list comprehension

I have a list of dicationaries list_dic each containing the keys id;name. From those keys I’d like create two lists.

I would like to use a list comprehension for this task, e.g.

list_id = [a['id'] for a in list_dic]
list_name = [a['name'] for a in list_dic]

The issue here is I’m looping twice which is probably not a smart thing to do.

Is there a way to use a list comprehension looping only once?

# Pseudo
list_id, list_name  = [a['id'], a['name'] for a in list_dic]

PS

I tried helper = [[a['id'], a['name']] for a in list_dic] which almost works. The problem is subsetting seems to require looping yet again (I hoped something like helper[:][0] would provide all ids).

Advertisement

Answer

Use zip:

list_id, list_name = zip(*[(a['id'], a['name']) for a in list_dic])
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement