Dictionary creation using dict comprehensions

Dictionary creation using dict comprehensions

In a previous Pythonic post we saw list comprehensions, an efficient Pythonic way to create lists.  I hope you got hooked and started using list comprehensions where your code could benefit from them.

Similar to list comprehensions, Python has a similar feature that’s applicable to dictionaries. The fancy name? Yes, dictionary comprehensions or dict comprehenions.

Without much babbling and tralala, here are dict comprehensions:

As you can see the basic construct for a dict comprehension is identical to a list comprehension. But instead of wrapping our construct in square brackets we surround it with curly braces. The value returned by our expression inside the dict comprehension should also return a key:value pair.

The official Python documentation has a small paragraph on dict comprehensions.

Leave a Reply

Your email address will not be published. Required fields are marked *