Udacity CS 101: Dictionary

We are introduced to another complex data types in Python: Dictionary. Dictionaries are created using curly braces, and entries in a dictionary are key-value pairs:


Something similar, but not.
Image courtesy of Wikipedia

alphabets = { 'a':1, 'b':2, 'c':3 }

Essentially a dictionary functions like a hash table, given a particular key, a its value is returned. A dictionary is mutable, just like a list. After creating a dictionary, we can append new key-value pairs, and we can modify individual key and values.

Remember how we refer to elements in strings and lists, we used the square brackets:

string[-1] # will give us the last character of the string

list[0] # will give us the first element of the list

For dictionaries its a little bit different:

print alphabets['a'] # will give us the value of the key 'a'

alphabets['a'] = 4 # will change the value of key 'a' to 4

print alphabets # so now the dictionary becomes { 'a':4, 'b':2, 'c':3 }

We can also use the in operator:

print 'd' in alphabets # will return False

The useful thing about a dictionary is that you can add key-value pairs on the fly:

alphabets['d'] = 4 # will create a new key 'd' in the dictionary, with the value 4

Like lists, dictionaries can be listed. A dictionary can contain elements which are dictionaries themselves!

alphabets = {}

alphabets['a'] = { 'page': 1, 'entries': 20, }

alphabets['b'] = { 'page': 30, 'entries': 10, }

print alphabets['a'] # will give us { 'page': 1, 'entries': 20, }

print alphabets['a']['page'] # will give us 1

This Udacity post references Udacity CS 101 Unit 5 Chapters 29, 30, 31 and 32.

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s