Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retain an item in python dictionary? [duplicate]

I've a dictionary my_dict and a list of tokens my_tok as shown:

my_dict = {'tutor': 3,
      'useful': 1,
      'weather': 1,
      'workshop': 3,
      'thankful': 1,
      'puppy': 1}

my_tok = ['workshop',
          'puppy']

Is it possible to retain in my_dict, only the values present in my_tok rather than popping the rest? i.e., I need to retain only workshop and puppy.

Thanks in advance!

like image 553
Sailesh Avatar asked Sep 03 '25 08:09

Sailesh


2 Answers

Just overwrite it like so:

my_dict = {k:v for k, v in my_dict.items() if k in my_tok}

This is a dictionary comprehension that recreates my_dict using only the keys that are present as entries in the my_tok list.

As said in the comments, if the number of elemenst in the my_tok list is small compaired to the dictionary keys, this solution is not the most efficient one. In that case it would be much better to iterate through the my_tok list instead as follows:

my_dict = {k:my_dict.get(k, default=None) for k in my_tok}

which is more or less what the other answers propose. The only difference is the use of .get dictionary method with allows us not to care whether the key is present in the dictionary or not. If it isn't it would be assigned the default value.

like image 71
Ma0 Avatar answered Sep 04 '25 20:09

Ma0


Going over the values from the my_tok, and get the results that are within the original dictionary.

my_dict = {i:my_dict[i] for i in my_tok}
like image 21
Mathias711 Avatar answered Sep 04 '25 21:09

Mathias711