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)
  4.  
  5. mydict = {'apple':'red', 'banana':'yellow', 'orange':'purple'}
  6.  
  7. print from_keys(mydict, 'apple orange'.split())
  8. # {'orange': 'purple', 'apple': 'red'}

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.