0

What is a convenient way of making a copy of a dictionary and only keep entries that are relevant to you?

Here I try to create a dictionary newdict:

mydict = {'A':'dog',
           'B':'cat',
           'C':'mouse'}

list_of_keys = ['A', 'B']
newdict = mydict[list_of_keys]

This syntax does not work. How would I create newdict which looks like this:

newdict{'A':'dog', 'B':'cat'}

Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132

2 Answers2

1

Use dict comprehension like this -

new_dict = {key : value for key, value in mydict.items() if key in list_of_keys}
kuro
  • 3,214
  • 3
  • 15
  • 31
1

you can use this, here's the source: Dictionary keys match on list; get key/value pair

mydict = {'A':'dog',
           'B':'cat',
           'C':'mouse'}

list_of_keys = ['A', 'B']

new_dict = {k: mydict[k] for k in list_of_keys if k in mydict}

print(new_dict) //output: {'A': 'dog', 'B': 'cat'}
Aeria
  • 118
  • 10