36
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.

HSRAO
  • 373
  • 1
  • 3
  • 4

6 Answers6

100

use dict comprehensions

alphabet =  {k.lower(): v for k, v in alphabet.items()}
styvane
  • 59,869
  • 19
  • 150
  • 156
13

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.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
3
d1 = {'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}
print dict((k.lower(), v) for k, v in d1.iteritems())

You may please visit Solution page

Community
  • 1
  • 1
Pralhad Narsinh Sonar
  • 1,406
  • 1
  • 14
  • 23
1
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}
newAlphabet = {}

for key, value in alphabet.iteritems():
    newAlphabet[key.lower()] = value
print newAlphabet
heinst
  • 8,520
  • 7
  • 41
  • 77
0
new_dict = {}
for letter in alphabet:
    number = alphabet[letter]
    new_dict.update({letter.lower():number})
Mathias711
  • 6,568
  • 4
  • 41
  • 58
-2
#!/usr/bin/python
# -*- coding: utf-8 -*-

import ast

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}

s=str(alphabet).lower()

alphabet=ast.literal_eval(s)

print alphabet

OUTPUT

{' ': 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}

Alex Ivanov
  • 695
  • 4
  • 6