Python Study Groups Resources for people learning Python

Exercise - Dictionary Keys

Given a pretty standard dictionary:

d = {
  'Jane': 33,
  'Elena': 17,
  'Margery': 28,
  'Savannah': 21
}

And a list of desired keys:

keys = ['Elena', 'Savannah']

How can you return a filtered version of d, without affecting what's stored in the original d?

What if the dictionary is more complex?

d = {
  'Jane': {
    'age': 33,
    'location': 'San Francisco'
  },
  'Elena': {
    'age': 17,
    'location': 'Petaluma'
  }
}

keys = ['age']

Try writing tests before working on the filter code itself. The specification of keys is up to you - can you think of edge cases where the format above is going to fail?