+ 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
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.
+ 7
d = dict(zip(range(3), 'abc'))
+ 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'}
0
thanks 🙏 all!!)