Dictionaries
Objective
After working through this lesson, you’ll be able to
Write Python code using dictionaries.
Introductory Problem
Create a list named friends of 3 of your friends. Create another list named towns of the 3 towns that they live in. Print these lists.
Dictionaries
A dictionary is a container that keeps associations between keys and values. Every key in a dictionary has an associated value. Keys are unique but a value may be associated with several keys. The dictionary structure is also known as a map or a hash table because it maps a unique key to a value.
Dictionary Functions and Operations
d = {} | Creates a new empty dictionary. |
d = {k1:v1,k2:v2,... , kn:vn} | Creates a new dictionary called d that contains the initial items provided. Each item consists of a key (k) and value (v) separated by a colon. |
d[key] | Returns the value associated with the given key. |
len(d) | Returns the number of items in dictionary d. |
key in d key not in d | The in operator is used to test if a key is in the dictionary. |
d[key] = value | Adds a new key/value item to the dictionary if the key does not exist. If the key does exist, it modifies the value associated with the key. |
d.get(key) | Returns the value associated with the given key. |
d.pop(key) | Removes the key and its associated value from the dictionary. |
d.keys() | Returns a sequence containing all keys of the dictionary. |
d.values() | Returns a sequence contains all the values of the dictionary. |
for key in d: print(key) | Iterates over keys in a dictionary. |
Examples
Example 1
Create a dictionary called d with 3 of your friends names and the towns they live in. Print the dictionary using a for loop.
Example 2
You are riding the bus and make new friends and you want to add them to your dictionary. Rita lives in West Milford and Karla lives in Haledon. Add these friends to your dictionary and print.
Example 3
Sadly, your friend Sofia moves away never to be seen or heard from again. Remove her from your dictionary. Print how many friends you have left.
Example 4
Your friend wants to quiz you on what towns your friends live in. Print the friend’s name and then ask the user what town he/she lives in. If the user gets the answer correct, print “Correct!”. Else print “Incorrect”.
Last updated