Ender Look
Ender Look

Reputation: 2401

How to make a nested list comprehension (Python)

I have this dictionary:

>>> times
{'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}

I want to make this output, the order of the values matters!:

0 1 0 0 1 0 0 0 0
# 0 1 0 | 0 1 0 | 0 0 0     ===   time | time_d | time_up   items of the list

For been more exactly I want a list like this:

[0,1,0,0,1,0,0,0,0]

Not use print().

Without a list comprehension I can do:

tmp = []
for x in times.values():
    for y in x:
        tmp.append(y)

I tryied using some list comprehensions but anyone works, like this two:

>>> [y for x in x for x in times.values()]
[0,0,0,0,0,0,0,0,0]

>>> [[y for x in x] for x in times.values()]
[[0,0,0],[0,0,0],[0,0,0]

How can I solve this with in one line (list comprehension))?

Upvotes: 2

Views: 328

Answers (4)

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

Take key and value from dictionary and append it into a list.

times={'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}
aa=[]
for key,value in times.iteritems():
    aa.append(value)
bb = [item for sublist in aa for item in sublist] #Making a flat list out of list of lists in Python
print bb

Output:

[0, 1, 0, 0, 0, 0, 0, 1, 0]

Upvotes: 0

VPfB
VPfB

Reputation: 17282

This will work also in Python 2:

[x for k in 'time time_d time_up'.split() for x in times[k]]

Upvotes: 0

developer_hatch
developer_hatch

Reputation: 16224

If I understood the question, you have to take the values, and then flat:

Edit, with users @juanpa.arrivillaga and @idjaw I think I undertand better the question, if the order matters, so you can use orderedDict:

import collections

times = collections.OrderedDict()

times['time'] = [0,1,0]
times['time_d'] = [0,1,0]
times['time_up'] = [0,0,0]

def get_values(dic):
  return [value for values in times.values() for value in values]


print(get_values(times))

Now, if you change the dict, the result came in order:

times['time_up2'] = [0,0,1]

get_values(times)

it gives me:

[0, 1, 0, 0, 1, 0, 0, 0, 1]

If the order doesn't matter:

times = {'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}

def get_values(dic):
  return [value for values in times.values() for value in values]


print(get_values(times))

Upvotes: 2

idjaw
idjaw

Reputation: 26570

You already know what values you want based on your dictionary, so just stick to being explicit about what you want from your dictionary when crafting your list:

d = {'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}
v = [*d['time'], *d['time_d'], *d['time_up']]
print(v)

Output:

[0, 1, 0, 0, 1, 0, 0, 0, 0]

Upvotes: 3

Related Questions