Dictionaries

Definitions

All of the compound data types we have studied in detail so far — strings, lists, and tuples — are sequential collections.

The items in the collection are ordered from left to right and they use integers as indices to access the values they contain.

Dictionaries are a different kind of collection. They are Python’s built-in mapping type. A map is an unordered, associative collection.

The association, or mapping, is from a key, which can be any immutable type, to a value, which can be any Python data object.

Create dictionary

dictionary literal

new_dictionary = {} 
eng2sp = {'three': 'tres', 'one': 'uno', 'two': 'dos'}

eng2sp = {}
eng2sp['one'] = 'uno'
eng2sp['two'] = 'dos'
eng2sp['three'] = 'tres'

dictionary constructor

dict() # not talked about yet

Work with data in a dictionary

del statement removes a key-value pair from a dictionary

updating value (from above)

number of items:

Methods

Method

Parameters

Description

keys

none

Returns a view of the keys in the dictionary

values

none

Returns a view of the values in the dictionary

items

none

Returns a view of the key-value pairs in the dictionary. It is (key, value) tuple.

get

key

Returns the value associated with key; None otherwise

get

key,alt

Returns the value associated with key; alt otherwise

More methods in python documentation

!!! Alert view looks like a list but is not of list type. Must be converted.

Skipping .keys()

It is used so often, it got implemented as default looping, and for loop iterating over a dictionary implicitly iterates over its keys.

.keys() vs .items()

Prevent no key in dictionary

Hand-coded:

Built-in way:

Aliasing and Copying

Because dictionaries are mutable, you need to be aware of aliasing.

Make copies instead

Sparse Matrices

A matrix is a two dimensional collection, typically thought of as having rows and columns of data:

sparse matrix

Represented in code as:

But the awful amount of zeros is making it really inefficient. In fact, only three of the data values are nonzero. This type of matrix has a special name. It is called a sparse matrix.

An alternative representation is to use a dictionary.

Access data with the default value assigned:

To display the matrix of size n:m loop the range, asking for each key.

Matrix does not have to be a square!

Last updated

Was this helpful?