# Mapping Data Type

#Basic#Data Type

In Python there is a mapping type called dictionary (dict for short). It is used to associate (map) keys (names) to some arbitrary values (objects).

Just like the idea of Yellow pages, where we can easily look for a plumber's phone number, with the help of a dict we access the values within the dictionary by the names.

# Dict

dict is constructed by key/value pairs. We use {} to denote a dictionary and : to separate a pair of key and value.

Say, we are to create a dictionary for contact numbers.

contacts = {
  "Jack": "1234567890",
  "Jill": "4567890123",
  "John": "7890123456",
  "Jane": None,
}
1
2
3
4
5
6

# access values in the dict

We can access each of the values stored in a dict by its key.

print(contacts["Jack"])
print(contacts["Jane"])
1
2

We can not only read values from a dict but also modify them.

contacts["Jane"] = "111222333"
contacts["Jack"] = "1234567890 #1"
1
2

# functions of dict

We use len() to get the number of items in a dictionary.

print(len(contacts))
1

We use keys() to get all the keys from a dict.

print(contacts.keys())
1

Similarly we use values() to get all the values from a dict.

print(contacts.values())
1

We can use items() to get all the (key, value) pairs.

print(contacts.items())

print(list(contacts.items()))
1
2
3

We use get(key[, default]) to get the value from a dict. If the key does not exist in the dictionary, it will return the default value.

Note that default is optional, the default value of default is None.

print(contacts.get("Jack"))
print(contacts.get("Oscar"))
print(contacts.get("Tim", "2223334444"))
1
2
3

We can use update([other]) to update the key/value pairs from the other dictionary.

 


 


 


contacts.update()
print(contacts)

contacts.update({"Penny": "8882229999"})
print(contacts)

contacts.update({"Penny": "4441113333"})
print(contacts)
1
2
3
4
5
6
7
8

We can use pop(key[, default]) to remove an item from a dictionary. The associated value will return. If the key does not exist in the dictionary, default will return if it is given. Otherwise, an error will raise.

number = contacts.pop("Jack")
print(number)
print(contacts)

default_number = contacts.pop("Adam", "000")
print(default_number)

contacts.pop("Daisy")
1
2
3
4
5
6
7
8

We can use copy() to create a shallow copy of the dictionary.

duplicate = contacts
duplicate["John"] = "7890123456 #111"
print(duplicate)
print(contacts)

duplicate = contacts.copy()
duplicate["John"] = "7890123456"
print(duplicate)
print(contacts)
1
2
3
4
5
6
7
8
9

what does shallow mean?

We will talk about the difference between by reference and by value in future.

We can use clear() to remove all items in a dictionary.

contacts.clear()
print(contacts)
1
2

# operators for dict

| would merge keys and values of two dictionaries. However the values of the dictionary on the right hand side of | has higher priority for same keys.



 


a = {1: "a"}
b = {2: "b", 3: "c", 1: "d"}
c = a | b
print(c)
1
2
3
4

And we can chain | with = to assign the new dictionary to the original dictionary.



 


a = {1: "a"}
b = {2: "b", 3: "c", 1: "d"}
a |= b
print(a)
1
2
3
4

We can use in to check if a key exists in a dictionary

print(1 in {1: "a"})
print(100 in {1: "a"})
1
2

# iterate the dict

We can use the for loop to iterate the dictionary.

 


for name in contacts:
    print(f"{name}'s phone number is {contacts[name]}.")
1
2

key/value pairs can be retrieved together.

 


for name, number in contacts.items():
    print(f"{name}'s phone number is {number}.")
1
2

# create a dict from list

We can also create a dictionary from a list, if the list contains key/value pairs.

For example,

pairs = [
    ("Jack", "1234567890"),
    ("Jill", "4567890123"),
    ("John", "7890123456"),
    ("Jane", None),
]
contacts = dict(pairs)
1
2
3
4
5
6
7

If we have keys and values in two separate lists, we can first generate a list of key/value pairs, then convert to dictionary.

names = ["Jack", "Jill", "John", "Jane"]
numbers= ["1234567890", "4567890123", "7890123456", None]
contacts = dict(zip(names, numbers))
1
2
3

what about zip?

It makes an iterator that aggregates elements from each of the iterables. See reference (opens new window).

a = range(10)
b = range(20, 30)
c = range(40, 50)
z = zip(a, b, c)
print(list(z))
1
2
3
4
5

# complex dictionary

The key/value pairs in a dictionary can be complex to fit your needs. Say you need to the contacts dictionary to store only the phone number but also address.

contacts = {
    "John": {
        "number": "1234567890",
        "address": "123 main st",
    },
    "Jack": {
        "number": "4567890123",
        "address": "456 main st",
    },
}

print(contacts)

for name, d in contacts.items():
    print(f"{name}'s phone number is {d['number']}.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Or we can create a grade_book dictionary to keep track of the grades for a total of 5 courses.

grade_book = {
    "Jack": [80, 81, 90, 92, 99],
    "John": [66, 100, 88, 98, 70, 80, 79],
    "Jill": [88, 59, 100],
}

for name, grades in grade_book.items():
    print(f"{name}'s average grades is {sum(grades) / len(grades)}")
1
2
3
4
5
6
7
8

# Assignment 11

Create a Python script named salaries.py and then put the following dictionary in it.

salaries = {
    "emp1": {"name": "Austin", "salary": 6500},
    "emp2": {"name": "Bill", "salary": 6500},
    "emp3": {"name": "Katherine", "salary": 8000},
}
1
2
3
4
5

Next, please change Bill's salary to 8500 and add another employee (emp4) to the salaries dictionary. emp4's name is Dora and her salary is 10000.

Finally, calculate and print the total number of employees and the average salary.

A sample run looks like the following.

python salaries.py
This company has 4 employees and the average compensation is 8250.0.
1
2
Sample Solution
salaries = {
    "emp1": {"name": "Austin", "salary": 6500},
    "emp2": {"name": "Bill", "salary": 6500},
    "emp3": {"name": "Katherine", "salary": 8000},
}

salaries["emp2"]["salary"] = 8500
salaries.update({"emp4": {"name": "Dora", "salary": 10000}})

size = len(salaries)
total_salaries = sum([emp["salary"] for emp in salaries.values()])

print(
    f"This company has {size} employees and the average compensation is {total_salaries/size}."
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15