remove last element in a dictionary of lists in python

Viewed 14524

What's a more pythonic or efficent way of removing the last element of each list, in a dictionary of lists?

For example, take this:

listDict = {'tom': [-2,10,2,-8], 'sam': [-9,-10,-10,-7]}

And transform it into this:

listDict = {'tom': [-2,10,2], 'sam': [-9,-10,-10]}

This is what I'm currently doing:

new = {}
for t,item in listDict.iteritems():
    new[t] = [item[0], item[1], item[2]]
listDict= new
5 Answers

If you are able to use pandas, given this dict:

listDict = {'tom': [-2,10,2,-8], 'sam': [-9,-10,-10,-7]}

Remove the last element like so:

import pandas 
df = pandas.DataFrame(data=listDict)
new = df[:-1]
print(new)

Which produces:

   tom  sam
0   -2   -9
1   10  -10
2    2  -10

If you want it as a dict then:

print(new.to_dict('list'))

Which produces:

{'tom': [-2, 10, 2], 'sam': [-9, -10, -10]}
Related