Home Dictionaries in Python
Post
Cancel

Dictionaries in Python

A dictionary lists key-value pairs, which could also be thought of as associated values where a key matches to the associated value. Let’s look at a few examples.

1
2
3
# Dictionary - mapping between values
house = {'bedrooms': 3, 'bathrooms': 2, 
         'city': 'Kelowna', 'price': 250000}
1
house['price']
1
## 250000
1
2
course = {'Data Science': ['DATA100', 'DATA200', 'DATA300'],
            'Science': ['SCIENCE100', 'SCIENCE200', 'SCIENCE300']}
1
course['Data Science']
1
## ['DATA100', 'DATA200', 'DATA300']

What if we wanted to turn the following information into a dictionary.

NameIDCampusCourses
Dan12345678OkanaganDATA100, ENGL100, HIST100, CHEM100

This is how we would do this:

```{.python .fold-hide} student = {‘Name’ : ‘Dan’, ‘ID’ : 12345678, ‘Campus’ : ‘Okanagan’, ‘Courses’: [‘DATA100’, ‘ENGL100’, ‘HIST100’, ‘CHEM100’]} student

1

{‘Name’: ‘Dan’, ‘ID’: 12345678, ‘Campus’: ‘Okanagan’, ‘Courses’: [‘DATA100’, ‘ENGL100’, ‘HIST100’, ‘CHEM100’]}

```

This post is licensed under CC BY 4.0 by the author.