How to Create a Special Dictionary with a String in Python


In this example, we will learn how to accept a string and create a dictionary with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

wordList = input("Please input the string separated by SPACE: ").split()
dict1 = {}
for word in wordList:
    if word[0] not in dict1.keys():
        dict1[word[0]] = []
        dict1[word[0]].append(word)
    else:
        if word not in dict1[word[0]]:
            dict1[word[0]].append(word)
print("The generated dictionary is: ", dict1)
print("The key-value paris in the dictionary: ")
for key,value in dict1.items():
    print(key,":",value)

Output:

Please input the string separated by SPACE: Python is an easy to learn, powerful programming language
The generated dictionary is: {'i': ['is'], 'l': ['learn,', 'language'], 't': ['to'], 'a': ['an'], 'P': ['Python'], 'p': ['powerful', 'programming'], 'e': ['easy']}
The key-value paris in the dictionary: 
i : ['is']
l : ['learn,', 'language']
t : ['to']
a : ['an']
P : ['Python']
p : ['powerful', 'programming']
e : ['easy']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments