Archive

Posts Tagged ‘dict comprehension’

Python – “dict comprehension”

February 4, 2013 1 comment

I learned a new way to initialize dictionaries that I had never seen before, and I thought I’d share it with you. I previously blogged about three ways of creating dictionaries in Python. I showed that you can use an iterable of (key, value) tuples to initialize a dict:

professions_dict = dict(zip(names, professions))

Another way along these same lines is to perform the iteration within a list comprehension. Say that we have an iterable of Person objects, each of which has a name and profession. The professions_dict could be created as follows:

professions_dict = dict([(x.name, x.profession) for x in people])

What I didn’t realize is you can skip the tuples and call to dict, and use the comprehension within the dictionary literal itself:

professions_dict = {x.name: x.profession for x in people}

In my opinion this is much cleaner. The syntax and official documentation can be found in 5.2.5. Displays for sets and dictionaries.

Advertisements