11

Suppose i have a string "abcdefghijklmnopqrstuvwxyz"and i want to initialize dictionary keys with those values.

alphabet = 'abcdefghijklmnopqrstuvwxyz'

alphabetDict = dict()
for char in alphabet:
    alphabetDict[char] = 0

Is there a better way of doing that?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
user1767754
  • 23,311
  • 18
  • 141
  • 164

6 Answers6

21

You can use dict.fromkeys() method -

>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> alphaDict = dict.fromkeys(s,0)
>>> alphaDict
{'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l': 0, 'e': 0, 'a': 0, 'j': 0, 'c': 0, 'o': 0, 'f': 0, 'v': 0, 'x': 0, 'z': 0, 'r': 0}

From documentation -

fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None.

Please note, you should not use this if value is something mutable like list or another dict , etc. As the value is only evaluted once when you call the method fromkeys() , and all keys point to the same object.

You can use this for immutable types as value like int, str , etc.


Also, you do not need to specify the s or alphabet string, you can instead use string.ascii_lowercase . Example -

>>> import string
>>> alphaDict = dict.fromkeys(string.ascii_lowercase,0)
>>> alphaDict
{'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l': 0, 'e': 0, 'a': 0, 'j': 0, 'c': 0, 'o': 0, 'f': 0, 'v': 0, 'x': 0, 'z': 0, 'r': 0}
Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
6

You can use dictionary comprehensions in Python.

alphabetDict = {char: 0 for char in alphabet}

Dictionaries (Python Docs)

There is a minor difference between this answer and Anand's above. Dict comprehensions evaluate the value for every key, while fromkeys only does it once. If you're using things like ints, this poses no problem. However, if you do

d = {key: [] for key in <some set>}
d[3].append(5)
print(d[2])

gives you

[]

and you have distinct lists, while

d = dict.fromkeys(<some set>, [])
d[3].append(5)
print(d[2])

gives you

[5]

will map all the keys to the same list.

Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60
3

Yes, you can do that in one line using dictionary comprehensions.

In [1]: alphabet = 'abcdefghijklmnopqrstuvwxyz'

In [2]: {x:0 for x in alphabet} # dictionary comprehension
Out[2]: 
{'a': 0,
 'b': 0,
 'c': 0,
 'd': 0,
 'e': 0,
 'f': 0,
 'g': 0,
 'h': 0,
 'i': 0,
 'j': 0,
 'k': 0,
 'l': 0,
 'm': 0,
 'n': 0,
 'o': 0,
 'p': 0,
 'q': 0,
 'r': 0,
 's': 0,
 't': 0,
 'u': 0,
 'v': 0,
 'w': 0,
 'x': 0,
 'y': 0,
 'z': 0}
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
0

Tried with another approach.

dict(zip(alphabets, '0'*len(alphabets)))
Vineesh
  • 253
  • 2
  • 7
0

If you need a dictionary with different values instead of a constant value, you may create one like below with the use of random module:

>>> import random
>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> my_dict = dict([ (ch, random.randint(1,len(alphabet)) ) for ch in alphabet ]  )
>>> my_dict
{'a': 17, 'b': 15, 'c': 3, 'd': 5, 'e': 5, 'f': 13, 'g': 7, 'h': 1, 'i': 3, 'j': 12, 'k': 11, 'l': 7, 'm': 8, 'n': 23, 'o': 15, 'p': 7, 'q': 9, 'r': 19, 's': 17, 't': 22, 'u': 20, 'v': 24, 'w': 26, 'x': 14, 'y': 7, 'z': 24}
>>>

I creates dictionaries like above when I need a dictionary with random values for testing purposes.

Another way to create a dictionary with each char of a text with character count.

>>> char_count = lambda text, char: text.count(char)
>>> text = "Genesis 1 - 1 In the beginning God created the heavens and the earth. 2 Now the earth was formless and desolate, and there was darkness upon the surface of the watery deep, and God's active force was moving about over the surface of the waters."
>>> my_dict = dict( [ ( char, char_count(text, char) ) for char in text ]  )
>>> my_dict
{'G': 3, 'e': 32, 'n': 13, 's': 15, 'i': 5, ' ': 45, '1': 2, '-': 1, 'I': 1, 't': 17, 'h': 12, 'b': 2, 'g': 3, 'o': 12, 'd': 10, 'c': 5, 'r': 12, 'a': 19, 'v': 4, '.': 2, '2': 1, 'N': 1, 'w': 6, 'f': 6, 'm': 2, 'l': 2, ',': 2, 'k': 1, 'u': 4, 'p': 2, 'y': 1, "'": 1}

Explanation:
1. lambda function counts number of occurrences of a characters.
2. Call lambda function for each character in text to get the count of that particular character.

Note: You may improve this code to avoid duplicate calls for repeated characters.

Using dictionary comprehension may be easier than all above:

{ char:(text.count(char)) for char in text }
Robert Ranjan
  • 1,538
  • 3
  • 19
  • 17
0

In order to avoid duplication as mentioned by @Robert Ranjan , we do it this way

>>> import string
>>> char_count = lambda text, char: text.count(char)
>>> allAscii = list(string.printable)
>>> # alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> text = "Genesis 1 - 1 In the beginning God created the heavens and the earth. 2 Now the earth was formless and desolate, and * @ there was darkness upon the surface of the watery deep, and God's active force was moving about over the surface of the waters."
>>> # my_dict = dict( [ ( char, char_count(text, char) ) for char in alphabet]  
>>> my_dict = dict( [ ( char, char_count(text, char) ) for char in allAscii]
>>> for eachKey in my_dict:  
        print(repr(eachKey), ': ', my_dict[eachKey], ' ', end=' || ')    
'0' :  0   || '1' :  2   || '2' :  1   || '3' :  0   || '4' :  0   || '5' :  0   || '6' :  0   || '7' :  0   || '8' :  0   || '9' :  0   || 'a' :  19   || 'b' :  2   || 'c' :  5   || 'd' :  10   || 'e' :  32   || 'f' :  6   || 'g' :  3   || 'h' :  12   || 'i' :  5   || 'j' :  0   || 'k' :  1   || 'l' :  2   || 'm' :  2   || 'n' :  13   || 'o' :  12   || 'p' :  2   || 'q' :  0   || 'r' :  12   || 's' :  15   || 't' :  17   || 'u' :  4   || 'v' :  4   || 'w' :  6   || 'x' :  0   || 'y' :  1   || 'z' :  0   || 'A' :  0   || 'B' :  0   || 'C' :  0   || 'D' :  0   || 'E' :  0   || 'F' :  0   || 'G' :  3   || 'H' :  0   || 'I' :  1   || 'J' :  0   || 'K' :  0   || 'L' :  0   || 'M' :  0   || 'N' :  1   || 'O' :  0   || 'P' :  0   || 'Q' :  0   || 'R' :  0   || 'S' :  0   || 'T' :  0   || 'U' :  0   || 'V' :  0   || 'W' :  0   || 'X' :  0   || 'Y' :  0   || 'Z' :  0   || '!' :  0   || '"' :  0   || '#' :  0   || '$' :  0   || '%' :  0   || '&' :  0   || "'" :  1   || '(' :  0   || ')' :  0   || '*' :  1   || '+' :  0   || ',' :  2   || '-' :  1   || '.' :  2   || '/' :  0   || ':' :  0   || ';' :  0   || '<' :  0   || '=' :  0   || '>' :  0   || '?' :  0   || '@' :  1   || '[' :  0   || '\\' :  0   || ']' :  0   || '^' :  0   || '_' :  0   || '`' :  0   || '{' :  0   || '|' :  0   || '}' :  0   || '~' :  0   || ' ' :  47   || '\t' :  0   || '\n' :  0   || '\r' :  0   || '\x0b' :  0   || '\x0c' :  0   ||
>>> 
akraf
  • 2,965
  • 20
  • 44
vdogra
  • 1