I want to create a dictionary of even numbers with the keys being consecutive integers using dictionary comprehension

The output should be:


I used 2 lines of code ie one line being the list comprehension to get the even numbers and the second being the dictionary comprehension to get the desired output.

The code i used is as follows:

evens=[number for number in range(1,10) if number%2==0]
even_dict={k:evens[k-1] for k in range(1,len(evens)+1)}

My question is instead of using 2 lines of code, can we use a single line of code which involves only dictionary comprehension to get the desired output?

2 Answers

olinox14 On

According to what is your desired output, you can simply do:

d = {x: 2*x for x in range(1, 5)}
tobias_k On

The way you have it now, you have to define evens before since you are using it in two places in the dict comprehension: To iterate the indices, and to get the actual element. Generally, whenever you need both the index and the element, you can use enumerate instead, possible with start parameter if you want to offset the index:

even_dict = {i: x for i, x in enumerate(evens, start=1)}

Now you only need evens once, and thus you could "inline" it into the dict comprehension:

even_dict = {i: x for i, x in enumerate([number for number in range(1,10) if number%2==0], start=1)}

But you do not need that inner list comprehension at all; to get the even numbers, you could just use range with step parameter:

even_dict = {i: x for i, x in enumerate(range(2, 10, 2), start=1)}

And, finally, in this particular case, you would not even need that, either, as you can just multiply the key with two to get the value, as shown in @olinox's answer.