Reputation: 3511
I have a very long dictionary
mydict = {
"6574": [],
"3234": [1],
"7014": [],
"0355": [3],
"1144": [2],
# …
}
I need to get all keys that have a non-empty list.
mytruedict = {}
for k, v in mydict.items():
if v:
mytruedict[k]=v
I was wondering if there is a one-line approach to it.
Upvotes: 1
Views: 22
Reputation: 82765
Using dict
Ex:
mydict = {
"6574": [],
"3234": [1],
"7014": [],
"0355": [3],
"1144": [2]
}
print( dict((k, v) for k, v in mydict.items() if v) )
#or
print( {k: v for k, v in mydict.items() if v } ) #dict comprehension
Output:
{'3234': [1], '1144': [2], '0355': [3]}
Upvotes: 3