Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove last element in a dictionary of lists in python

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
like image 442
Zach Avatar asked Aug 11 '12 05:08

Zach


People also ask

How can I remove last element from a list?

pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.

How do I remove the last 3 elements from a list in Python?

The pop() method will remove the last element from the list, So to remove the last k elements from the Python List, we need to perform the pop() operation k times.

Which method is used to remove the last item from dictionary?

The popitem() method is used to remove the last item added to the dictionary.

How do you pop the last element of a list in Python?

In Python, the pop() method is used to remove the last element of the given list and return the removed item. The pop() method can optionally accept an integer argument. It is the index of the element that we want to remove, so if we call exampleList. pop(0) , the first element will be removed and returned.


2 Answers

Blender's answer grows very inefficient as the lengths of the lists increases, compared to this solution:

for k, v in listDict.items():
    v.pop()

For your example listDict, the difference is not big, just 27%. But using a dict with 100 keys and lists of length from 50 to 100, and popping 50 of them, the dict comprehension method takes more than 12 times longer. This is because this solution modifies the existsing lists instead of creating copies of each list every time.

I'm afraid that there is no one-liner version of this, unless you're cheating. The reason I mention this at all is to prevent that some dofus feels compelled to point it out in comments. Please don't use dict/list comprehensions for side effects.

Of course you can do it on one line as follows, but PEP8 says "rather not":

for k, v in listDict.items(): v.pop()
like image 106
Lauritz V. Thaulow Avatar answered Nov 03 '22 21:11

Lauritz V. Thaulow


I would use a dictionary comprehension:

new_dict = {key: value[:-1] for key, value in listDict.items()}

For older Python versions you'll have to use the dict() constructor:

new_dict = dict((key, value[:-1]) for key, value in listDict.items())
like image 37
Blender Avatar answered Nov 03 '22 23:11

Blender