Dictionary

Dictionary (Associative Array, map, symbol table) is a data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection.

Common Operations:

  • Adding a pair

  • Removing a pair

  • Modify an existing pair

  • Lookup of a value associated with a particular key

Aside: This concept is an introduction to concepts similar to: hash table and search trees

Defining a Dictionary in Python 3

Dictionaries also use {} like sets; however, their individual item format is very different.

Each item in a dictionary be a pair of key: value.
# Dictionary Example
sammy = {
    'username': 'sammy',
    'online': True,
    'followers': 42
}

# There are 3 items: each with their unique addresses and value
# Accessing
print('Sammy dict:', sammy)
print('Username:', sammy['username'])
print('Online Status:', sammy['online'])
print('Follower Count:', sammy['followers'])

Dictionary Properties

Each item in a dictionary is a key, value pair.

Keys

Keys are unique address for a dictionary valueโ€™s location

Key Properties:

  • Must be immutable (strings, numbers, tuples, frozenset)

  • Unique; therefore, two same key values cannot exist in a single dictionary

    • NEWEST CREATED ITEM with a duplicate KEY superceeds the previous declaration

Values

Values of a dictionary within a key can be any data type.

Updating a Dictionary

  • We can modify existing values by referencing the key

  • We can add new values to a dictionary by creating a new key

  • We can overwrite a value at an existing key by referencing and recreating the value for it

Deletion with Dictionary

  • We can delete a key hence deleting the value connected to the key

  • We can empty out the entire dictionary

  • We can delete the dictionary (uncommonly used)

Membership

We can use the in and not in operators to check if a key exists in a dictionary

Built-in Functionsโ€™ Interactions w/ Dictionaries

Duplicate a Dictionary and Copy Keys Only

Dictionary Methods

To help power this awesome data structure, it has good set of methods for us to use.

Let A and B be a dictionary

  • A.keys() โ€“> Returns a sequence of keys/addresses in A

  • A.values() โ€“> Returns a sequence of item values in A

  • A.items() โ€“> Returns a sequence of key,item pairs in A

  • A.get(address) โ€“> Returns the item value at address

  • A.update(B) โ€“> Extends A with the dictionary of key,value pairs of B

Iterating a Dictionary

  • We will be taking advantage of three iteration methods

    1. iterating the keys

    2. iterating the values

    3. iterating the key, value pairs by unpacking

dict() Constrcutor Dictionary Comprehension

We can turn other data types to dictionaries.

Also similar to lists, tuples, and sets, dictionaries also support comprehension.

Note:

  • We must specify where the keys are and where the values.

Last updated