ByteBoard Notes Notes

Create a dictionary to store names of states and their capitals

Informatics Practices XI · Experiment 15 of 36 · Python

★ CBSE suggested11-IPPython programs
Expt. No.15
Page No.30

States and capitals dictionary

Aim

To write a Python program that stores states and their capitals in a dictionary, displays them, and finds the capital of a state entered by the user.

Concepts used

Algorithm

  1. Create a dictionary with states as keys and capitals as values.
  2. Display each state and capital with a loop.
  3. Input a state; if it is a key, display its capital, otherwise display a message.

Program

# States and their capitals capitals = {"Rajasthan": "Jaipur", "Kerala": "Thiruvananthapuram",            "Odisha": "Bhubaneswar", "Punjab": "Chandigarh",            "Assam": "Dispur"} for state in capitals:    print(state, "->", capitals[state]) state = input("Enter a state: ")if state in capitals:    print("Capital of", state, "is", capitals[state])else:    print(state, "is not in the dictionary")

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python states_capitals.py
Rajasthan -> Jaipur Kerala -> Thiruvananthapuram Odisha -> Bhubaneswar Punjab -> Chandigarh Assam -> Dispur Enter a state: Odisha Capital of Odisha is Bhubaneswar
Run 2
$ python states_capitals.py
Rajasthan -> Jaipur Kerala -> Thiruvananthapuram Odisha -> Bhubaneswar Punjab -> Chandigarh Assam -> Dispur Enter a state: Goa Goa is not in the dictionary

✓ Printed by running this program, not typed by hand.

Result

All five states were listed with their capitals. Odisha's capital was found as Bhubaneswar; Goa is not a key, so the program said so.

Viva voce: what the examiner may ask

01What is a key-value pair?

An item of a dictionary: the key (state) is used to look up its value (capital).

02What does state in capitals check?

Whether state is one of the keys.

03What happens on capitals["Goa"] if Goa is not a key?

Python raises KeyError.

Variations for the lab test

  1. Add a new state with its capital, then display the dictionary.
  2. Display only the states whose capital starts with "B".
  3. Display the number of states using len().
! Common mistake Typing "odisha" in lowercase does not match the key "Odisha"; keys are case-sensitive.
Back to the 11-IP index