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?
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With