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

<

Leave a Reply

Your email address will not be published.