Strings and dictionaries are the two most used data structures in Python. We use strings for text analysis in Python. On the other hand, a dictionary is used to store key-value pairs. In this article, we will discuss how to create a dictionary from a string in Python.
Create a Dictionary From a String Using for Loop
To create a dictionary from a string in Python, we can use a python for loop. In this approach, we will create a dictionary that contains the count of all the characters in the original string. To create a dictionary from the given string, we will use the following steps.
- First, we will create an empty python dictionary using the
dict()
function. - Next, we will use a for loop to iterate through the characters of the string.
- While iteration, we will first check if the character is already present in the dictionary or not. If yes, we will increment the value associated with the character in the dictionary. Otherwise, we will assign the character as a key and 1 as the associated value to the dictionary.
After executing the for loop, we will get the dictionary containing the characters of the string as keys and their frequency as values. You can observe this in the following example.
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict()
for character in myStr:
if character in myDict:
myDict[character]+=1
else:
myDict[character]=1
print("The dictionary created from characters of the string is:")
print(myDict)
Output:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 2, 'F': 1, 'r': 2, 'B': 1, 'e': 2, 'g': 1, 'i': 1, 's': 1}
Dictionary From a String Using the Counter Method
To create a dictionary from a string in python, we can also use the Counter()
method defined in the collections module. The Counter()
method takes a string as an input argument and returns a Counter object. The Counter object contains all the characters of the string as keys and their frequencies as the associated values. You can observe this in the following example.
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict(Counter(myStr))
print("The dictionary created from characters of the string is:")
print(myDict)
Output:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 2, 'F': 1, 'r': 2, 'B': 1, 'e': 2, 'g': 1, 'i': 1, 's': 1}
Dictionary From a String Using Dict.fromkeys() Method
We can also create a dictionary from a string in python using the fromkeys()
method. The fromkeys()
method takes a string as its first input argument and a default value as its second argument. After execution, it returns a dictionary containing all the characters of the string as keys and the input value as the associated values for each key. If you want to provide a default associated value to all the keys of the dictionary, you can use the fromkeys()
method to create a dictionary from a string as shown below.
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict.fromkeys(myStr,0)
print("The dictionary created from characters of the string is:")
print(myDict)
Output:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': 0, 'y': 0, 't': 0, 'h': 0, 'o': 0, 'n': 0, ' ': 0, 'F': 0, 'r': 0, 'B': 0, 'e': 0, 'g': 0, 'i': 0, 's': 0}
If you don’t want to pass any default value to the fromkeys()
method, you can choose to omit it. In this case, all the keys of the dictionary created from the string will have None as their associated values. You can observe this in the following example.
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict.fromkeys(myStr)
print("The dictionary created from characters of the string is:")
print(myDict)
Output:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': None, 'y': None, 't': None, 'h': None, 'o': None, 'n': None, ' ': None, 'F': None, 'r': None, 'B': None, 'e': None, 'g': None, 'i': None, 's': None}
Using Ordereddict.fromkeys() Method
Instead of a dictionary, you can also obtain an ordered dictionary from a string in Python. If you want to provide a default associated value to all the keys of the dictionary, you can use the fromkeys()
method to create an ordered dictionary from a string. The fromkeys()
method takes a string as its first input argument and a default value as its second argument. After execution, it returns an ordered dictionary containing all the characters of the string as keys. You can observe this in the following example.
from collections import OrderedDict
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=OrderedDict.fromkeys(myStr,0)
print("The dictionary created from characters of the string is:")
print(myDict)
Output:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
OrderedDict([('P', 0), ('y', 0), ('t', 0), ('h', 0), ('o', 0), ('n', 0), (' ', 0), ('F', 0), ('r', 0), ('B', 0), ('e', 0), ('g', 0), ('i', 0), ('s', 0)])
If you don’t want to pass any default value to the fromkeys()
method, you can choose to omit it. In this case, all the keys of the ordered dictionary created from the string will have None as their associated values. You can observe this in the following example.
from collections import OrderedDict
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=OrderedDict.fromkeys(myStr)
print("The dictionary created from characters of the string is:")
print(myDict)
Output:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
OrderedDict([('P', None), ('y', None), ('t', None), ('h', None), ('o', None), ('n', None), (' ', None), ('F', None), ('r', None), ('B', None), ('e', None), ('g', None), ('i', None), ('s', None)])
Conclusion
In this article, we have discussed different ways to create a dictionary from a string in Python. To learn more about python programming, you can read this article on string manipulation. You might also like this article on python simplehttpserver.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.