remove last element in a dictionary of lists in python - Stack Overflow
Last Key in Python Dictionary - Stack Overflow
How can I remove a key from a Python dictionary? - Stack Overflow
[Python] How do I remove the brackets from a list in a dict
Have you tried something like this?:
for station, value in self.stationDict.items():
self.stationDict[station] = [value[0][0], value[1], value[2]]More on reddit.com
Videos
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())
It seems like you want to do that:
dict.keys()[-1]
dict.keys() returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.
Since a dictionary is unordered*, it's doesn't make sense to get the last key of your dictionary.
Perhaps you want to sort them before. It would look like that:
sorted(dict.keys())[-1]
Note:
In Python 3, the code is
list(dict)[-1]
*Update:
This is no longer the case. Dictionary keys are officially ordered as of Python 3.7 (and unofficially in 3.6).
If insertion order matters, take a look at collections.OrderedDict:
An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
In [1]: from collections import OrderedDict
In [2]: od = OrderedDict(zip('bar','foo'))
In [3]: od
Out[3]: OrderedDict([('b', 'f'), ('a', 'o'), ('r', 'o')])
In [4]: od.keys()[-1]
Out[4]: 'r'
In [5]: od.popitem() # also removes the last item
Out[5]: ('r', 'o')
Update:
An OrderedDict is no longer necessary as dictionary keys are officially ordered in insertion order as of Python 3.7 (unofficially in 3.6).
For these recent Python versions, you can instead just use list(my_dict)[-1] or list(my_dict.keys())[-1].
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomicโit is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.