Reputation: 966
I have a dictionary of lists each with a different number of elements. I'd like to add default values to the beginning of each list to make them all the same size.
So, if I start with...
data = {'data1': [1,2,3], 'data2': [12,23,34,45,44], 'data3': [7,8,9,10], 'data4': [71, 72, 73, 74, 75, 76, 78], 'data5': []}
I would like to end up with:
data1: [0, 0, 0, 0, 1, 2, 3]
data2: [0, 0, 12, 23, 34, 45, 44]
data3: [0, 0, 0, 7, 8, 9, 10]
data4: [71, 72, 73, 74, 75, 76, 78]
data5: [0, 0, 0, 0, 0, 0, 0]
I have come up with the following code:
maxlen = 0
for d in data:
if maxlen < len(data[d]):
maxlen = len(data[d])
for d in data:
if len(data[d]) < maxlen:
data[d] = [0] * (maxlen - len(data[d])) + data[d]
This works, but is there a better way to do this?
Upvotes: 1
Views: 1924
Reputation: 117866
You can figure out which list is the longest, then pad out each of the other lists with zeroes in a dict comprehension.
>>> longest = max(len(i) for i in data.values())
>>> data = {key: [0]*(longest-len(value)) + value for key,value in data.items()}
>>> data
{'data5': [0, 0, 0, 0, 0, 0, 0],
'data1': [0, 0, 0, 0, 1, 2, 3],
'data4': [71, 72, 73, 74, 75, 76, 78],
'data3': [0, 0, 0, 7, 8, 9, 10],
'data2': [0, 0, 12, 23, 34, 45, 44]}
Upvotes: 9