Python Forum
Deleting value from dictionary. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Deleting value from dictionary. (/thread-10370.html)



Deleting value from dictionary. - dbdb12 - May-18-2018

I was wondering how to remove values from a key if the length of the value was less than a certain amount. I'm not trying to remove the entire key/item. All keys and values are strings in this case.


RE: Deleting value from dictionary. - Larz60+ - May-18-2018

Do you mean like this?
>>> thedict = {
...     'aaaa': {
...         '123': 'One Two Three',
...         '234': 'Two Three Four'
...     },
...     'bbbb': {
...         '123': 'One Two Three',
...         '456': 'Four five six',
...     }
... }
>>> thedict
{'aaaa': {'123': 'One Two Three', '234': 'Two Three Four'}, 'bbbb': {'123': 'One Two Three', '456': 'Four five six'}}
>>> del thedict['bbbb']['123']
>>> thedict
{'aaaa': {'123': 'One Two Three', '234': 'Two Three Four'}, 'bbbb': {'456': 'Four five six'}}
>>>



RE: Deleting value from dictionary. - dbdb12 - May-18-2018

Yes, but is it possible to not hard-code it? For example, if your'e given a dictionary, and you need to remove values from keys where the length of the word is lets say less than 5.
So like:
dictionary = {"hello":["hey", "dinosaur", "dragon"], "fire:["volcano", "explosion", "boom"]}
So i need to remove "hey" and "boom".

I apologize if i'm difficult to understand. I'm new to python and still not quite familiar with the terminology.


RE: Deleting value from dictionary. - buran - May-18-2018

(May-18-2018, 01:38 AM)dbdb12 Wrote: All keys and values are strings in this case.
(May-18-2018, 02:00 AM)dbdb12 Wrote: So like:
dictionary = {"hello":["hey", "dinosaur", "dragon"], "fire:["volcano", "explosion", "boom"]}
well, note that your statement and your example contradict to each other. In your example the key is a string, the value is a list. And that list has number of elements that are strings.
anyway, something like this should work:
dictionary = {"hello":["hey", "dinosaur", "dragon"], "fire":["volcano", "explosion", "boom"]}
new_dict = dict()
for key, value in dictionary.items():
    new_dict[key] = [s for s in value if len(s)>5]
print(new_dict)