Python Dictionary

1) Create & Print a Dictionary

Ask the user to enter a name and age, store them in a dictionary, and print it.


2) Access a Value

Given:

student = {"name": "Alice", "age": 20}

Print the value of "name".


3) Change a Value

Update the age in:

student = {"name": "Bob", "age": 18}

to a new age and print.


4) Add a New Key-Value Pair

Start with:

info = {"city": "Toronto"}

Add "country": "Canada" and print.


5) Remove a Key

Given:

Remove "age" and print.


6) Get All Keys

Create a dictionary and print only its keys.


7) Get All Values

Create a dictionary and print only its values.


8) Loop Through Dictionary

Given a dictionary, loop through and print each key and its value.

Example output:


9) Check Membership

Ask the user for a key and check if it exists in the dictionary.


10) Dictionary Length

Create a dictionary and print how many key-value pairs it has.


11) Clear Dictionary

Create a dictionary, clear it using clear(), and print it.


12) Copy Dictionary

Make a copy of a dictionary and print both original and copy.


13) Nested Dictionary

Create a dictionary containing another dictionary inside it, then print both.

Example:


14) Update Dictionary

Use update() to add multiple key–value pairs at once.


15) Pop an Element

Use pop() to remove a key and print the removed value.


16) Default Value with get()

Try to access a key using get() that might not exist, and provide a default message.

Example:


17) Loop Keys Only

Loop through and print just the dictionary’s keys.


18) Loop Values Only

Loop through and print just the dictionary’s values.


19) Create Dictionary from Two Lists

Given:

Create a dictionary using a loop.


20) Count Character Occurrences

Ask the user for a word. Create a dictionary where the keys are characters and values are the count of each character.

Example:


📝 Tips for Students

  • Dictionaries are unordered collections of key–value pairs.

  • Keys must be unique and hashable (e.g., strings, numbers, tuples).

  • Common operations:

    • dict[key] — access value

    • dict[key] = value — add or update

    • .keys(), .values(), .items() — iterate


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated