Intermediate Python Session Part 3 of 4

 

Dictionary Comprehensions

 

We are now on part 3 of Intermediate Python, dictionary comprehensions or dict comprehension for short. PEP 274 is a follow up to list comprehensions, but for creating dictionaries.

The constructing of dict comprehensions are very similar to list comprehensions, but they use { } curly brackets to enclose code and provide a key : value mapping for the object.

 
Here in the example below is a dictionary that maps a string to an integer:
The code below is using the example above and producing it as a list comprehension and turning it into a dictionary using the dict function:

 

Dict Comprehensions come in handy when you want pair up values in a object, and to organize them in a dict. But turning an object into a sequence with length of 2 can be inconvenient or inefficient from a memory or performance standpoint. So, they do not work on infinite sequences, because Python has no construct of an infinitely large dictionaries.

 

 

 

 

 

 

 

 

 

 

 

 

Count of a List of Random Integers
Here is an example of getting the count of random numbers from a list, and arranging them by number and how times it appears on the list in a dictionary format:

 

 

The key on the dict represents the random integer and the value represents how many times that integer appears on the list (rand_nums).

 

Now that we have gone through this intro to dict comprehensions, the next and final part of our series to Intermediate Python will be on set comprehensions.

 

 

 

 

 

 

Check our next webinars

Subscribe

Recent Post