Posted By

magicrebirth on 05/17/10


Tagged

dictionary


Versions (?)

'Dictionary Comprehensions'


 / Published in: Python
 

Although Python doesn't have built-in dictionary comprehensions, you can do something pretty close with little mess or code. Just use .iteritems() to turn your dict into a list, throw it in a generator expression (or list comprehension), and then cast that list back into a dict.

For example, say I have a dictionary of name:email pairs, and I want to create a dictionary of name:isemailatadot_com pairs:

  1. emails = {'Dick': '[email protected]', 'Jane': '[email protected]', 'Stou': '[email protected]'}
  2.  
  3. email_at_dotcom = dict( [name, '.com' in email] for name, email in emails.iteritems() )
  4.  
  5. # email_at_dotcom now is {'Dick': True, 'Jane': True, 'Stou': False}
  6.  
  7.  
  8.  
  9.  
  10. # ANOTHER OPTION TO CREATE DICTS ON THE FLY:
  11.  
  12. d = dict([("n= %s" % x, x) for x in range(10)])
  13.  
  14. # {'n= 9': 9, 'n= 8': 8, 'n= 3': 3, 'n= 2': 2, 'n= 1': 1, 'n= 0': 0, 'n= 7': 7, 'n= 6': 6, 'n= 5': 5, 'n= 4': 4}

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: krone on April 24, 2013

If you are in 2.7+ I think you can do the following without having to explicitly call the dict constructor

{name: email for name, email in emails.iteritems()}

You need to login to post a comment.