Bertelsmann Tech Scholarship Challenge, Python, Udacity

Python – Data Structures: Dictionaries


Dictionaries are slightly different than the rest. In dictionaries we supply our own indexes. The index is often referred to as a key. Keys can be strings, integers, floats, or even tuples.  We then supply the value of the key.

You might have noticed that dictionaries require a different structure within the brackets to assign keys to the values. They use a colon : to separate the value from its key.

Example of a dictionary

my_dictionary = {1:"cat", 2:"dog", 3:"horse", 4:"fish"}


my_dictionary2 = {"1":"cat", "2":"dog", "3":"horse", "4":"fish"}

We can look up items by referring to their keys

-> "dog"

-> "horse"

We can add new items to a dictionary by placing the item in square brackets like this:

my_dictionary[5] = "monkey"
-> {1: 'cat', 2: 'dog', 3: 'horse', 4: 'fish', 5: 'monkey'}

We can check whether a value is in a dictionary the same way we check whether a value is in a list or set with the in keyword. Dictionaries also have a method that’s also useful, get. get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn’t found.

print("dog" in my_dictionary)
-> True

-> False

Identity Operators

Keyword Operator
is evaluates if both sides have the same identity
is not evaluates if both sides have different identities

Compound Data Structures

We can have dictionaries inside dictionaries so that we are able to store more information.

Sort of like our contacts app

contacts = {"Sally":{"number": 1234567890, "email":"", "dob":"01-01-1980"}, "Bob"{"number": 2345678901, "email":"", "dob":"02-01-1998"}}

We now have two contacts and we can access Sally’s email by doing

sally_email = contacts["Sally"]["email"]

We can also add a new contact

Martha = {"number":5678901234, "email":"", "dob":"11-11-2000"}
contacts["Martha] = Martha
This is from Lesson 22:  Data Types and Operators Videos 29-35

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s