remove last element in a dictionary of lists in python - 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
How to remove empty dictionary value from list?
Yes the quotes (empty string) are considered values and you would use an if statement. Probably what I would suggest is a list comprehension:
[d for d in mylist if d['name']]
This creates a new list with each dictionary value in there if the value corresponding to the key 'name' is not an empty string. The empty string is a Falsey value in Python, so instead of checking if d['name'] != '' (which is also totally valid) you can just ask if d['name'].
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())
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.