Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all keys of a dictionary into lowercase [duplicate]

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.

like image 311
HSRAO Avatar asked Jun 09 '15 13:06

HSRAO


People also ask

How do I convert a dictionary to lowercase in Python?

We are also using the lower() function of Python String to convert the key text to lowercase.

Can you duplicate keys in dictionaries?

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.

Can dictionary have duplicate key values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Which method returns all the keys in a dictionary?

Python dictionary method keys() returns a list of all the available keys in the dictionary.


2 Answers

use dict comprehensions

alphabet =  {k.lower(): v for k, v in alphabet.items()} 
like image 163
styvane Avatar answered Sep 20 '22 13:09

styvane


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.

like image 22
Paul Rooney Avatar answered Sep 17 '22 13:09

Paul Rooney