Skip to content
Advertisement

How to drop pairs in dict

I want to drop value pairs in a dictionary if the first element contains a certain string (time or session), but keep the remaining pairs (word and group). dic1 is the one I have and dic2 is the one I would like.

I have written a one liner that removes the entire value element but thats not really what I want…I wonder where I am going wrong.

dic1 = dict({'a':[{'word': '3', 'group': 'a', 'time': 'nat'},
                  {'word': '1', 'group': 'b', 'session':'199'},
                  {'word': '0', 'group': 'c'}]})

dic2 = dict({'a':[{'word': '3', 'group': 'a'},
                  {'word': '1', 'group': 'b'},
                  {'word': '0', 'group': 'c'}]})

{k :[x for x in dic1[k] if (x.keys()) == {'word', 'group'}] for k, in dic1}

Advertisement

Answer

The unwanted keys are inside x here:

{k :[x for x in dic1[k] if (x.keys()) == {'word', 'group'}] for k, in dic1}

You need one more dict comprehension inside your comprehension:

out = {k: [{k2:v2 for k2,v2 in x.items() if k2 not in ('time', 'session')} for x in v1] for k, v1 in dic1.items()}

Output:

{'a': [{'word': '3', 'group': 'a'},
  {'word': '1', 'group': 'b'},
  {'word': '0', 'group': 'c'}]}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement