Python Dictionary Comprehension

george udosen
2 min readMar 20, 2020

Ok may be it was easy for you to understand but I didn’t get it the first time and now that I have let me use a simple example to help others that will get stuck.

Here is the example:

def Convert(lst):res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}return res_dct# Driver codelst = ['a', 1, 'b', 2, 'c', 3]print(Convert(lst))

In this example gotten from geekforgeek.org a python list is being converted to a dictionary using the dictionary comprehension method. And the result would be this

{'b': 2, 'c': 3, 'a': 1}

Ok, let me start like this. The structure of the python dictionary is basically “key: value” and if you look at the comprehension above you won’t immediately see this structure but that’s what that comprehension is trying to achieve howbeit in some complicated “not so clear” way. Anyways lets break it down

  • This “lst[i]” is the dictionary key and
  • Every thing here lst[i + 1] for i in range(0, len(lst), 2) is the value.

So we pick a key “lst[i]” which should be ‘a’ from our test example and add a value of “lst[i + 1] (remember we are starting from zero and increment by two), which is ‘1’. Then we pick the next key, which would be “b” (remember i was 0 and is now 2 [step 2]) and the value 2 (with index gotten from “i + 1”, 2 + 1 = 3) and so on and so forth till…

So dictionary comprehensions are simple say with this key “lst[i]” associate it with the value gotten from this operations “lst[i + 1] for i in range(0, len(lst), 2) “ and the last but not the least make the result into a dict with the “surrounding” “{}”, called a typecasing!

--

--

george udosen

DevOps | FullStack developer | Python::Flask | GCP Cloud Certified | AWS & AZURE Cloud Savy | Linux Sysadmin | Google IT Support