Filter a dict based on a list of keys

/ Published in: Python
Save to your folder(s)

Copy this code and paste it in your HTML
  1. # Filter a dict
  2. def from_keys(d, iterator):
  3. return dict((i, d[i]) for i in iterator)
  5. mydict = {'apple':'red', 'banana':'yellow', 'orange':'purple'}
  7. print from_keys(mydict, 'apple orange'.split())
  8. # {'orange': 'purple', 'apple': 'red'}

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.