+ 2

Is there an any way to create dictionary by range like this ?

try: a = tuple (range (3)) print (a) b = list (range (3)) print (b) c = set (range (3)) print (c) d = dict (range (3)) print (d) except: print ("dict error") _____________________ output: (1,2,3) [1,2,3] {1,2,3} dict error

28th May 2019, 8:19 AM
Магомед Акуев
Магомед Акуев - avatar
4 odpowiedzi
+ 7
Unlike tuples, lists, and sets, dictionaries require a key-value pair for each entry. However, if you want all of your elements in the range to be keys with the SAME value, say, 42, then you can try this: d = dict.fromkeys(range(5), 42) But I think the dictionary comprehension as suggested by Jay is much cleaner and far more versatile.
28th May 2019, 10:25 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 7
d = dict(zip(range(3), 'abc'))
28th May 2019, 12:35 PM
Anna
Anna - avatar
+ 4
I am a little bit late with my comment. Coming back to Annas code you can slightly modify it, if you have already a list for the values: lst = ['xp', 'w3', 'ib'] d1 = dict(zip(range(3), lst)) print(d1) # result: {0: 'xp', 1: 'w3', 2: 'ib'}
28th May 2019, 4:42 PM
Lothar
Lothar - avatar
0
thanks 🙏 all!!)
28th May 2019, 6:05 PM
Магомед Акуев
Магомед Акуев - avatar