Home > Net >  delete specific keys from a dictionary based on a condition
delete specific keys from a dictionary based on a condition

Time:01-20

I have a dictionary like the follow:

   {'weather1': {428: 68253},
     'weather2': {1323: 68586, 1343: 68605, 1344: 68606},
     'weather3': {311: 68183, 312: 68184, 290: 68164},
     'weather4': {699: 68304, 721: 68323, 722: 68324},
     'weather5': {7260: 69942},
     'weather6': {15: 68095, 35: 68114, 36: 68115})

I want to delete the keys that have only one value. For example, I want to delete weather1 and weather5 and return the rest of the dictionary to a dictionary format

Any ideas?

CodePudding user response:

Assuming d the input. Use a simple dictionary comprehension:

out = {k:v for k,v in d.items() if len(v)>1}

Output:

{'weather2': {1323: 68586, 1343: 68605, 1344: 68606},
 'weather3': {311: 68183, 312: 68184, 290: 68164},
 'weather4': {699: 68304, 721: 68323, 722: 68324},
 'weather6': {15: 68095, 35: 68114, 36: 68115}}
  •  Tags:  
  • Related