This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

< 2.5 Data Structure - Sets | Contents | 2.7 Introducing Numpy Arrays >

Data Structure - Dictionaries

We introduced several sequential data type in the previous sections. Now we will introduce you a new and useful type - Dictionaries. It is a mapping type, which makes it a totally different type than the ones we talked before. Instead of using a sequence of numbers to index the elements (such as lists or tuples), dictionaries are indexed by keys, which could be a string, number or even tuple (but not list). A dictionary is a key-value pairs, and each key maps to a corresponding value. It is defined by using a pair of braces { }, while the elements are a list of comma separated key:value pairs (note the key:value pair is separated by the colon, with key at front and value at the end).

dict_1 = {'apple':3, 'oragne':4, 'pear':2}
{'apple': 3, 'oragne': 4, 'pear': 2}

Within a dictionary, elements are stored without order, therefore, you can not access a dictionary based on a sequence of index numbers. To get access to a dictionary, we need to use the key of the element - dictionary[key].

TRY IT! Get the element ‘apple’ from dict_1.


We could get all the keys in a dictionary by using the keys method, or all the values by using the method values.

TRY IT Get all the keys and values from dict_1.

dict_keys(['apple', 'oragne', 'pear'])
dict_values([3, 4, 2])

We could also get the size of a dictionary by using the len function.


We could define an empty dictionary and then fill in the element later. Or we could turn a list of tuples with (key, value) pairs to a dictionary.

TRY IT! Define an empty dictionary named school_dict and add value “UC Berkeley”:”USA”.

school_dict = {}
school_dict['UC Berkeley'] = 'USA'
{'UC Berkeley': 'USA'}

TRY IT! Add another element “Oxford”:”UK” to school_dict.

school_dict['Oxford'] = 'UK'
{'UC Berkeley': 'USA', 'Oxford': 'UK'}

TRY IT! Turn the list of tuples [(“UC Berkeley”, “USA”), (‘Oxford’, ‘UK’)] into a dictionary.

dict([("UC Berkeley", "USA"), ('Oxford', 'UK')])
{'UC Berkeley': 'USA', 'Oxford': 'UK'}

We could also check if an element belong to a dictionary using the operator in.

TRY IT! Determine if “UC Berkeley” is in school_dict.

"UC Berkeley" in school_dict

TRY IT! Determine whether “Harvard” is not in school_dict.

"Harvard" not in school_dict

We could also use the list function to turn a dictionary with a list of keys. For example:

['UC Berkeley', 'Oxford']

< 2.5 Data Structure - Sets | Contents | 2.7 Introducing Numpy Arrays >