简体   繁体   中英

How to automate the creation of a dictionnary in python

Hello dear community (and thank you in advance for your time and help).

I'am trying to do the simple letter cipher exercise during a python course. During the solution (I'am still strying to come up with) I want to creat two dictionnaries one with the alphabet as the keys and numbers as values: exemple alphabet_dict{"a":1,"b":2,"c":3,...... and another with the numbers as keys and the alphabet as values. I want to automate it or at least creat it with code instead of typing it in (it's more pythonic isn't it?) Here is where I'am stuck, here is my code:

import string
alphabet = string.ascii_lowercase

alpha_dict = {}

for char in alphabet:
   
    alpha_dict[char].append(i for i in range(1.26))

print(alpha_dict)

for the numbers dictionary, the code string.digit gives only up to 9, how to automate the creation of a dictionary up to 26 without typing it.

Many many thanks in advance.

You can try

import string

alphabet = string.ascii_lowercase
alpha_dict = {letter:index+1 for index,letter in enumerate(alphabet)}

You can reverse the order to get the other dictionary

use string.ascii_lowercase and convert to list type

import string

alphabet = list(string.ascii_lowercase)

alphabet: ascending order

alphabet_dict = {alphabet[idx] : idx + 1 for idx in range(len(alphabet))}

alphabet: descending order

alphabet_dict2 = {alphabet[idx] : idx + 1 for idx in range(len(alphabet)-1, -1, -1)}

I guess this is the code you are searching for:

import string
al_num = {}
num_al = {}
number = 1
for letter in string.ascii_lowercase:
    al_num[letter] = number
    num_al[number] = letter
    number+=1
print(al_num)
print(num_al)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}

Instead of creating variables, you can append dictionaries as an item of a list.

# Variable to store dictionaries
together = []

# run 10 times
for i in range(10):
    dictionary = {'index': i}
    together.append(dictionary)

print(together)

Then you will get:

[{'index': 0}, {'index': 1}, {'index': 2}, {'index': 3}, {'index': 4}, {'index': 5}, {'index': 6}, {'index': 7}, {'index': 8}, {'index': 9}]

Check out the chr and ord functions. They will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM