Program to create dictionary output from the given string

In this python function program, we will create a function to create dictionary output from the given string.

Dictionary:
A dictionary consists of a collection of key-value pairs.

What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.

Steps to solve the program
  1. Create a function fun.
  2. Use the def keyword to define the function.
  3. Pass a parameter i.e. string to the function.
  4. Create an empty dictionary.
  5. Create a list of the words in the string using split(” “).
  6. Use a for loop to iterate over the words in the list.
  7. Add the first letter and the last letter of the word as the key and the word as the value to the dictionary.
  8. Return the list.
  9. Pass the dictionary to the function while calling the function.
				
					def fun(string):
    a= {}
    l = string.split(" ")
    for word in l:
        a[word[0]+word[-1]] = word
    return a
fun("Python is easy li Learn")
				
			

Output :

				
					{'Pn': 'Python', 'is': 'is', 'ey': 'easy', 'li': 'li', 'Ln': 'Learn'}
				
			

Related Articles

get the square of all values in the given dictionary.

print a list of prime numbers from 1 to 100.

Leave a Comment