Home > Mobile >  How to drop pairs in dict
How to drop pairs in dict

Time:01-22

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}

CodePudding user response:

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'}]}

CodePudding user response:

Here's the code which only keeps needed fields:

    dic2 = {k :[{'word':x['word'], 'group' : x['group']} for x in dic1[k]] for k, in dic1}
  •  Tags:  
  • Related