4

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!

Sailesh
  • 115
  • 2
  • 10

3 Answers3

2

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.

Community
  • 1
  • 1
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • 2
    I would swap the iterator and the `if` statement since there are only a very limited amount of keys you want to retain an an element check is in general faster on a dictionary. – Willem Van Onsem Jan 12 '17 at 13:26
  • @WillemVanOnsem Very true. Updated the answer – Ma0 Jan 12 '17 at 13:29
2

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}
Mathias711
  • 6,568
  • 4
  • 41
  • 58
2

Create a new copy

You can simply overwrite the original dictionary:

new_dic = {token:my_dict[key] for key in my_tok if key in my_dict}

Mind however that you construct a new dictionary (perhaps you immediately writ it to my_dict) but this has implications: other references to the dictionary will not reflect this change.

Since the number of tokens (my_tok) are limited, it is probably better to iterate over these tokens and do a contains-check on the dictionary (instead of looping over the tuples in the original dictionary).

Update the original dictionary

Given you want to let the changes reflect in your original dictionary, you can in a second step you can .clear() the original dictionary and .update() it accordingly:

new_dic = {token:my_dict[key] for key in my_tok if key in my_dict}
my_dict.clear()
my_dict.update(new_dic)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555