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
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.
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.
The popitem() method is used to remove the last item added to the dictionary.
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.
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()
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With