+ 2

Is there a more efficient way to do this?

I want to make a dict where every key is a letter and the value is the letter with the same place in the reverse alphabet. Is there a way to do it without the for loop? alph = "abcdefghijklmnopqrstuvwxyz" alph_r = alph[::-1] alph_dict = {} for x in range(0, len(alph)): alph_dict[alph[x]] = alph_r[x]

9th Aug 2020, 5:35 PM
Erick
Erick - avatar
10 Réponses
+ 18
very similar to Louis solution: from string import ascii_lowercase as chars res = dict(zip(chars, chars[::-1]))
9th Aug 2020, 6:13 PM
Lothar
Lothar - avatar
+ 14
alph = "abcdefghijklmnopqrstuvwxyz" alph_dict = {i:j for i,j in zip(alph,alph[::-1])} #for loop is still there, just more compact
9th Aug 2020, 6:01 PM
Louis
Louis - avatar
+ 10
Lothar very nice! Yours is better. And so we keep learning from one another.
9th Aug 2020, 6:19 PM
Louis
Louis - avatar
+ 3
Louis I see, thanks!
9th Aug 2020, 6:09 PM
Erick
Erick - avatar
+ 3
Steven, what Erick is asking for, is to create a dict for handling the cryption of characters. Therefore he made his try that gives a dict like: {'a': 'z', 'b': 'y', 'c': 'x', ...', 'y': 'b', 'z': 'a'} What your code is doing is a bit different. It just creates a dict with characters of alphabeth, and a consecutive number as value.
11th Aug 2020, 9:34 AM
Lothar
Lothar - avatar
+ 2
Lothar Cool!
9th Aug 2020, 6:34 PM
Erick
Erick - avatar
0
Since my variant already written by Lothar The alternative code is follow(acording to c++ inverse string element detection) k=len(alph) alph={alph[i]:alph[k-1-i] for i in range(k)} also which variant is faster?! someone know what faster use comprehension use for loop or slice of list. sinse coping in memory took time in case of huge data
9th Aug 2020, 6:52 PM
george
george - avatar
0
Sherif please share link! i didn't know.
11th Aug 2020, 7:07 AM
Oma Falk
Oma Falk - avatar
0
Probably no
11th Aug 2020, 4:30 PM
Nikhil Patil
Nikhil Patil - avatar