Is there a more efficient way to do this? | SoloLearn: Learn to code for FREE!


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]

8/9/2020 5:35:04 PM


10 Answers

New Answer


very similar to Louis solution: from string import ascii_lowercase as chars res = dict(zip(chars, chars[::-1]))


alph = "abcdefghijklmnopqrstuvwxyz" alph_dict = {i:j for i,j in zip(alph,alph[::-1])} #for loop is still there, just more compact


Lothar very nice! Yours is better. And so we keep learning from one another.



Louis I see, thanks!


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.


Lothar Cool!


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


Sherif please share link! i didn't know.