Here, We are going to write python program to create a dictionary to store names of state and their capitals . We can use for loop to add item in dictionary. We can add items in dictionary without using for loop too. In this python program,we will create dictionary to store names of state and their capitals without using for loop .
Python program to create dictionary and add items without using for loop
# Creating dictionary
capitals = { "Maharashtra": "mumbai",
"Delhi" : "New Delhi",
"Uttar pradesh":"Lucknow",
"Tamil Nadu ": " Chennai"}
print("Original Dictionary : ")
print(capitals)
# adding item in dictionary
capitals['Punjab'] = 'Chandigarh'
# printing dictionary after adding item
print()
print("After adding item in dictionary :")
print("Updated Dictionary:")
print(capitals)
Output
Original Dictionary : {'Maharashtra': 'mumbai', 'Delhi': 'New Delhi', 'Uttar pradesh': 'Lucknow', 'Tamil Nadu ': ' Chennai'} After adding item in dictionary : Updated Dictionary: {'Maharashtra': 'mumbai', 'Delhi': 'New Delhi', 'Uttar pradesh': 'Lucknow', 'Tamil Nadu ': ' Chennai', 'Punjab': 'Chandigarh'}
Python program to create dictionary and add items using for loop
states = dict()
n = int(input("Enter the number of states :"))
for i in range(n):
state = input("Enter name of state :")
capital = input("Enter capital of state :")
states[state] = capital
print("Dictionary is created :",states)
t = input("Enter the name of state to display capital:")
print(states[t])
Output
Enter the number of states :4 Enter name of state :Maharashtra Enter capital of state :Mumbai Enter name of state :Delhi Enter capital of state :New Delhi Enter name of state :Uttar Pradesh Enter capital of state :Lucknow Enter name of state :Tamil Nadu Enter capital of state :Chennai Dictionary is created : {'Maharashtra': 'Mumbai', 'Delhi': 'New Delhi', 'Uttar Pradesh': 'Lucknow', 'Tamil Nadu': 'Chennai'} Enter the name of state to display capital:Delhi New Delhi
Python Programs with solutions
- To calculate EMI for amount, period and interest
- To calculate tax-GST/ income tax
- To find the largest and smallest numbers in a list
- To find third largest/ smallest number in a list
- To find sum of squares of the first hundred natural numbers
- To print the first n multiples of given number
- To count the number of vowels in a user entered string
- To print the words starting with particular alphabet in a user entered string
- To print the number of occurrences of a given alphabet in a given string