Home > Python > Python – “dict comprehension”

Python – “dict comprehension”

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.

  1. September 28, 2013 at 5:30 pm

    Lansing-born Mekamifu spare-time activities includes wedding, 70’s music, hunting.
    Nearly all her drive derives from visiting different countries like

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: