Dictionary Comprehension — Python programming

Jirateep T.
2 min readJun 13, 2022

--

Hi there, coders. Some of you guys reading this might be beginners trying to make your code look more elegant? Don’t freak out let me help you.

There’s a way to neater your code out that is called the Comprehension method which is nothing more than compressing multiple lines of codes into one. This can also apply to other various types of data sets like lists, sets, and tuples.

https://tenor.com/view/programmer-code-ape-working-gif-13305212

Let’s talk about dictionaries today. So, what’s Dictionary?

Dictionaries are data type in Python which let us to store data in key-value pair. Unlike other data type, Dictionary’s values is mutable but keys don’t. Items in the dictionary are enclosed within a pair of curly braces {}.

Here is what using a dictionary looks like:

my_dict = {a: 'car', b: 'bus'}

As in the above code;

  • It contains 2 key-value pairs of data which a and b are keys and ‘car’ and ‘bus’ are values.
  • We can use my_dict[“a”] to access the ‘car’ value as well as my_dict[“b”] to access the ‘bus’ value.

Now let’s use the comprehension method with iterable.

The syntax would be :

my_dict = {key:value for item in iterable}

Let’s print the table of keys with a squared value from range 1 to 6.

https://carbon.now.sh/

We can also set every key’s value to “True” by:

https://carbon.now.sh/

Time for something more advance, you think?

Let’s say we have 2 lists, one contains keys and one contains values. We can use the “zip()” function to zip those two lists to generate keys and value pairs.

The syntax would be:

my)dict = {key : value for (key,value) in zip(list1,list2)}

Let’s try it out

https://carbon.now.sh/

We can also add conditions to the dictionary comprehension to find specific data. The syntax is:

newdict = {key:value for (key,value) in olddict.items() if condition}

let me show you how to use it in the bigger picture:

https://carbon.now.sh/

Conclusions:

  • We can use dictionary comprehension to compress our code into one single making it looks neater than multiple lines of code.
  • We can adapt this method to use with any conditions in a single comprehensive line.
  • Warning: Using this method can sometimes consume more memory, therefore, making the code run slower.
  • Warning: Using too many conditions in a single comprehensive line can make it difficult to read and find errors if need to.

Links:

--

--

Jirateep T.
0 Followers

Junior Student in Bachelor’s degree on Artificial Intelligence Technology.