Two important Logics for using dictionary.
Here in this article, I am going to discuss two programs that will help in the deeper understanding of using dictionary datatype in Python.
So what is a dictionary?
In Python, a dictionary is a datatype that is used for storing key-value pairs just like a phone book or a real-life dictionary for example in a phone book if you want to find a phone number associated with a person you look up their name(key) and find associated phone number (the value).
So the two programs which deal with the operation of a dictionary where in alphabets are assigned a value for example a = 1,b = 2,c =3 ... z = 26. An in input is given of the for like "abc" so the output must generate 6 ie. 1+2+3.
So two types of dictionary is used
letter_to_value = {
"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
}
value_to_letter = {
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"
}
Code 1 using the "letter_to_value" dictionary
letter_to_value = {
"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
}
for key,values in letter_to_value.items():
print(f"key:{key} values: {values}")
x = "abcz" #input variable
sum1 = 0
for i in x:
if i in letter_to_value:
sum1+=letter_to_value[i]
print(sum1)
Code 2 using the "value_to_letter" dictionary
value_to_letter = {
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"
}
for key,values in value_to_letter.items():
print(f"key:{key} values: {values}")
x = "abcz"
sum1 = 0
for i in x:
for key,value in value_to_letter.items():
if value == i:
sum1+=key
print(sum1)
So through these programs, we can both compare the possibility of a dictionary can be used in different scenarios.