Reputation: 638
I have a dict of list a. I have a max value that corresponds to the largest list in a. I would like to create another list containing list a and add None values if the size of the list is smaller than my max value.
I have a code that works but I would like to use a List Comprehensions.
a = {'t': [3, 4, 2, 3], 'y': [7, 5]}
max_len = len(max(a.values(), key=len))
new_list = []
for i in a.values():
i.extend([None] * (max_len - len(i)))
new_list.append(i)
print(new_list)
Upvotes: 0
Views: 62
Reputation: 421
A very simple way to do this using list comprehension.
a = {'t': [3, 4, 2, 3], 'y': [7, 5]}
new_list = [j for i,j in a.items()]
print new_list
Upvotes: 0
Reputation: 33159
Instead of extending i
, add.
a = {'t': [3, 4, 2, 3], 'y': [7, 5]}
max_len = max(map(len, a.values())) # <- Also simplified this
new_list = [i + [None]*(max_len - len(i)) for i in a.values()]
print(new_list)
Upvotes: 2