Revision: 26931
Updated Code
at May 17, 2010 06:41 by magicrebirth
Updated Code
emails = {'Dick': '[email protected]', 'Jane': '[email protected]', 'Stou': '[email protected]'} email_at_dotcom = dict( [name, '.com' in email] for name, email in emails.iteritems() ) # email_at_dotcom now is {'Dick': True, 'Jane': True, 'Stou': False} # ANOTHER OPTION TO CREATE DICTS ON THE FLY: d = dict([("n= %s" % x, x) for x in range(10)]) # {'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}
Revision: 26930
Updated Code
at May 17, 2010 06:37 by magicrebirth
Updated Code
emails = {'Dick': '[email protected]', 'Jane': '[email protected]', 'Stou': '[email protected]'} email_at_dotcom = dict( [name, '.com' in email] for name, email in emails.iteritems() ) # email_at_dotcom now is {'Dick': True, 'Jane': True, 'Stou': False} # ANOTHER OPTION TO CREATE DICTS ON THE FLY: d = dict([(x, x) for x in range(10)]) # {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
Revision: 26929
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at May 17, 2010 06:34 by magicrebirth
Initial Code
emails = {'Dick': '[email protected]', 'Jane': '[email protected]', 'Stou': '[email protected]'} email_at_dotcom = dict( [name, '.com' in email] for name, email in emails.iteritems() ) # email_at_dotcom now is {'Dick': True, 'Jane': True, 'Stou': False}
Initial URL
Initial Description
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:is_email_at_a_dot_com pairs:
Initial Title
'Dictionary Comprehensions'
Initial Tags
Initial Language
Python