I’m supposed to program in Python, and I’ve only used Python for 3 weeks. I have to solve all kinds of problems and write functions as training. For one of my functions I use this line.
theDict = dict( [(k,v) for k,v in theDict.items() if len(v)>0])
However I can’t use anything I don’t fully understand or can’t fully explain. I understand the gist of the line, but, I can’t really explain it. So my instructor told me that to use this, i must learn ether everything about tuples and fully understand list comprehension, or i must write that in pure python.
The line basically looks into a dictionary, and inside the dictionary, its supposed to look for values that are equal to empty lists and delete those keys/values.
So, my question is, what would this line look like in pure, non list comprehension python?
I’ll attempt to write it because I want to try my best, and this isn’t a website where you get free answers, but you guys correct me and help me finish it if it doesn’t work.
Also another problem is that, the empty lists inside the ‘value’ of the dictionary, if they are empty, then they won’t be processed inside the loop. The loop is supposed to delete the key that is equal to the empty value. So how are you supposed to check if the list is empty, if the check is inside the loop, and the loop won’t have the empty array in its body?
for key,value in TheDict.items(): #i need to add 'if value:' somewhere,
#but i don't know how to add it to make it work, because
#this checks if the value exists or not, but if the value
#doesn't exist, then it won't go though this area, so
#there is no way to see if the value exists or not.
theDict[key]=value
If there is a better method to remove dictionary values that have a value of an empty list. please let me know.
And how will
theDict = dict( [(k,v) for k,v in theDict.items() if len(v)>0])
look like if it didn’t use a generator?
will look like(if you want new dictionary)
if you want to modify existing dictionary: