Skip to Main Content

Python for Basic Data Analysis

Start your data science journey with Python. Learn practical Python programming skills for basic data manipulation and analysis.

Dictionaries

Dictionaries are unordered collections of data and are represented with curly brackets  { } . Like lists, dictionaries are mutable(changeable) and indexed. With dictionaries, data is stored in a  key:value  format.

Syntax

myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020}

In this example, myCar is the variable that we have assigned our dictionary to.
"Brand", "Model" and "Year" are the keys, while "Hyundai", "Palisade" and "2020" are the values.


You can also type the dictionary out like this.

myCar = {
   "Brand": "Hyundai",
   "Model": "Palisade",
   "Year": 2020
}


Example

Accessing Elements

You can access the  values  of a dictionary by referring to its  key  name inside square brackets:

Syntax

myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020}
print(myCar["Model"])


Example

Adding Values

You can add new  key:value  pairs using the following method.

Syntax

myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020}

myCar["Color"] = "Wine Red"
print(myCar)

 

Example

Changing Values

You can change the  value  of a specific item by referring to its  key .

Syntax

myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020}

myCar["Model"] = "Genesis"
print(myCar)

 

Example

Removing Elements

We can remove an element using the pop method by referring to its  key .

Syntax

myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020}

myCar.pop("Model"
print(myCar)

 

Example

Video Guide

Exercises

1. Create a new dictionary database called myClass as an empty dictionary. Add the following key-value pairs:

Keys Values Types
"Instructor" "Anna" String
"Assistants" ["Ted", "Nat", "Wei Meng"] List
"Students" 20 Int

2. Add a fourth assistant to your database, named Mark

3. Someone from another class has joined this class. add the students count by 1

4. Print out everything you know about your database.

Expected Output:

{"Instructor": "Anna", "Assistants": ["Ted", "Nat", "Wei Meng", "Mark"], "Students": 21 }