1

Hi so I wanted to generate a dict of the python alphabet in the form

{'a':'a', 'b':'b', 'c':'c'....}

The link here was pretty helpful, but when I replace the last 0 in there with string.ascii.lowercase, I get this:

{'a': 'abcdefghijklmnopqrstuvwxyz', 'b': 'abcdefghijklmnopqrstuvwxyz', 'c': 'abcdefghijklmnopqrstuvwxyz'...}

So, how can I fix this?

Community
  • 1
  • 1

5 Answers5

2

You can try this way:

dict([(character,character) for character in string.ascii_lowercase])

Or another one:

dict(zip(string.ascii_lowercase,string.ascii_lowercase))
GAVD
  • 1,977
  • 3
  • 22
  • 40
0
characters = {}
for character in string.ascii.lowercase:
    characters[character] = character
Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42
0

Here is one way to make a shifted dictionary:

def shiftDict(i):
    i = i % 26
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    return dict(zip(alpha,alpha[i:] + alpha[:i]))

The for your original question shiftDict(0) returns what you asked for. As another example:

>>> d = shiftDict(3)
>>> d
{'u': 'x', 'w': 'z', 'e': 'h', 'r': 'u', 'o': 'r', 'c': 'f', 'x': 'a', 'i': 'l', 'k': 'n', 't': 'w', 'h': 'k', 'j': 'm', 'b': 'e', 'l': 'o', 'y': 'b', 'f': 'i', 's': 'v', 'q': 't', 'm': 'p', 'd': 'g', 'v': 'y', 'p': 's', 'g': 'j', 'z': 'c', 'n': 'q', 'a': 'd'}

But for Caesar shifts -- you might want to look into using the string translate method.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
0

What about using a dictionary and range?

>>> dict = {chr(ord('a') + i) : chr(ord('a') + i) for i in range(26)}
>>> dict
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd', 'g': 'g', 'f': 'f', 'i': 'i', 'h': 'h', 'k': 'k', 'j': 'j', 'm': 'm', 'l': 'l', 'o': 'o', 'n': 'n', 'q': 'q', 'p': 'p', 's': 's', 'r': 'r', 'u': 'u', 't': 't', 'w': 'w', 'v': 'v', 'y': 'y', 'x': 'x', 'z': 'z'}

And you can make a generic function

def gen_alpha_range(start, count):
    return {chr(ord(start) + i) : chr(ord(start) + i) for i in range(count)}

result = gen_alpha_range('A', 5)
print(result)

>>> {'A': 'A', 'C': 'C', 'B': 'B', 'E': 'E', 'D': 'D'}
Kevin Sabbe
  • 1,412
  • 16
  • 24
0
list1=list(map(chr,range(97,123)))

It will return the list which contains all the lowercase alphabets.

troy
  • 2,145
  • 2
  • 23
  • 31