Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert every character in a String to a Dictionary Key

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?

like image 784
user1767754 Avatar asked Sep 28 '15 05:09

user1767754


3 Answers

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}
like image 173
Anand S Kumar Avatar answered Oct 23 '22 17:10

Anand S Kumar


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.

like image 36
Snakes and Coffee Avatar answered Oct 23 '22 18:10

Snakes and Coffee


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}
like image 45
Rahul Gupta Avatar answered Oct 23 '22 18:10

Rahul Gupta