Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dictionary without using a for loop in 1 line of code?

This is my code:

dictionary = {}
for i in range(2, 15):
    dictionary[str(i)] = 0

Is it possible to create it with just one line of code?

like image 966
Jakub Bielan Avatar asked Dec 14 '25 08:12

Jakub Bielan


2 Answers

Use:

print(dict.fromkeys(range(2,15),0))

Or if want strings for dictionary keys:

print(dict.fromkeys(map(str,range(2,15)),0))

Or another way to make keys strings:

print(dict.fromkeys([str(i) for i in range(2,15)],0))
like image 68
U12-Forward Avatar answered Dec 16 '25 04:12

U12-Forward


Yes:

dictionary = {str(i): 0 for i in range(2, 15)}

This is called a dictionary comprehension. There are similar syntax structures for lists, generators, and sets.

like image 39
L3viathan Avatar answered Dec 16 '25 05:12

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!