alphabet = {'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, ' ':27}
Is there any way to convert all of the keys into lowercase? Note: There is a space at the end of the dict.
We are also using the lower() function of Python String to convert the key text to lowercase.
Why you can not have duplicate keys in a dictionary? You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
Python dictionary method keys() returns a list of all the available keys in the dictionary.
use dict comprehensions
alphabet = {k.lower(): v for k, v in alphabet.items()}
Just use a comprehension to run through the dictionary again and convert all keys to lowercase.
alphlower = {k.lower(): v for k, v in alphabet.iteritems()}
Result
{' ': 27, 'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
If you are using python 3, then use alphabet.items()
instead of iteritems
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With