Python 3 Fundamentals Week 12 - Dictionaries 課程筆記

Introduction

  • One of the most important data structures in Python
  • The abstract concept is to associate two things together, which is called an Associative Array (關聯式陣列) / Map (映射), and the dictionary is one concrete implementation of this concept.

Associative Arrays and Dictionaries

Hash Maps (aka Dictionaries)

  • Lookup speed is not affected by size of dictionary
  • Keys must be hashable (hence the term “hash map”)

An object is hashable if it has a hash value which never changes during its lifetime. – Python glossary

  • Hashable: strings, numerics
  • Non-Hashable: list
  • May be Hashable: tuple (depends on the elements in the tuple)

Python Dictionaries

  • The dictionary is a data structure that associates a value to a key
    • Key must be hashable type (ex. str, int, bool, float, …) and unique
    • Value can be any type
  • Type of dictionary is dict
  • The dictionary is a collection of key : value pairs
  • The dictionary is an iterable objects; not a sequence type (no ordering)
    • Values are looked up by key, not by index
  • The dictionary is a mutable collection

Dictionary Literals

Each key is separated from its value by a colon :, the items are separated by commas ,, and the whole thing is enclosed in curly braces {}.

d = {
    'symbol': 'AAPL',
    'date': '2024-01-01',
    'close': 300
}

Access Dictionary Items

Access the value by placing the key inside square brackets []

d = {
    'symbol': 'AAPL',
    'date': '2024-01-01',
    'close': 300
}

d['close']    


# Output: 
# 300

Replacing the Value of an Existing Key

Change the value by referring to its key

d = {
    'symbol': 'AAPL',
    'date': '2024-01-01',
    'close': 300
}

d['close'] = 285.355

Output

{'symbol': 'AAPL', 'date': '2024-01-01', 'close': 285.355}

Adding a New key:value Pair

Add an item to a dictionary by assigning a value to a new key.

  • If key exists, the value will be updated.
d = {
    'symbol': 'AAPL',
    'date': '2024-01-01',
    'close': 300
}

d['open'] = 265

Output

{'symbol': 'AAPL', 'date': '2024-01-01', 'close': 285.355, 'open': 265}

Deleting a key:value Pair

Use the del statement to remove an element from a dictionary.

d = {
    'symbol': 'AAPL',
    'date': '2024-01-01',
    'close': 300,
    'open': 265
}

del d['open']

Output

{'symbol': 'AAPL', 'date': '2024-01-01', 'close': 285.355}

Common Exceptions

  • KeyError

    • Trying to read a non-existent key
    • Trying to delete a non-existent key
  • TypeError

    • Trying to use a non-hashable object as a key
d = {
    'symbol': 'AAPL',
    'date': '2024-01-01',
    'close': 300
}

d[[10, 20]] = 10

Output

TypeError                                Traceback (most recent call last)
Cell In[11], line 1
----> 1 d[[10, 20]] = 10

TypeError: unhashable type: 'list'

Coding

hash()

hash(3.14)    # Output: 322818021289917443

Iterating Dictionaries

Default iteration is over the dictionary keys.

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

for k in d:
    print(k)

Output

a
b
c

Iterating over values

The values() method returns a view object that contains the values of the dictionary.

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

for v in d.values():
    print(v)

Output

1
2
3

Iterating over key:value Pairs

The items() method returns a list of tuples containing the key:value pairs of the dictionary.

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

for i in d.items():
    print(i)

Output

('a', 1)
('b', 2)
('c', 3)

Unpack dictionary

for k, v in d.items():
    print(f'{k} = {v}')

Output

a = 1
b = 2
c = 3

The keys() Method

Returns a view object that contains the keys of the dictionary, it is not useful since the default iteration is over the keys.

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

for k in d.keys():
    print(k)

Output

a
b
c

Insertion Order

  • In earlier versions of Python, there was no guaranteed iteration order.
  • Starting in Python 3.6, the iteration order reflects the insertion order. (Insertion order is the order in which the key:value pairs are listed out.)
d = {
    'a': 1, 
    'b': 2, 
    'c': 3
}

d['x'] = 24  # Add an item 'x'
del d['b']  # Remove item 'b'
d['c'] = 300  # Update the value of item 'c'
d['b'] = 200  # Add an item 'b'

for k, v in d.items():
    print(f'{k} = {v}')

Output

a = 1
c = 300
x = 24
b = 200

Working with Dictionaries

Dictionary Membership

Check if a Key Exists in a Dictionary.

  • IN: Returns true if the item exists, otherwise returns false.
  • NOT IN: Returns true if the item does not exist, otherwise returns false.
>>> d = {'a': 1, 'b': 2}
>>> 'a' in d
True
>>> 'x' in d
False
>>> 2 in d
False
>>> 'x' not in d
True

Useful Methods and Functions

Method / Function Description
d.clear( ) Removes all elements from d
d.copy( ) Returns a shallow copy of d
d.deepcopy( ) Creates a deep copy of d
len(d) Returns number of elements in d

d.clear( )

data = {
    3.14: 'π',
    'l': [1, 2, 3],
    'init': 0
}

data.clear()
print(data)

Output

{}

Methods to Create Dictionaries

Using the literal: key could be any object that is hashable

>>> d = {'a': 1, 'b': 2}

Using dict( ) method: key should be a valid variable name

>>> D = dict(x = 1, y = 2)
>>> D
{'x': 1, 'y': 2}
>>>

Using dict.fromkeys( ) method creates a new dictionary from the given iterable and values all set to specified value.

>>> dic = dict.fromkeys('python', 1)
>>> dic
{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}

>>> dic1 = dict.fromkeys([1, 2, 3], 'init')
>>> dic1
{1: 'init', 2: 'init', 3: 'init'}

>>> d = dict.fromkeys(['a', 'a'], 0)
>>> d
{'a': 0}

Creating Empty Dictionaries

>>> d = {}
>>> d
{}

>>> D = dict()
>>> D
{}

The get( ) Method

Returns the value for key in the dictionary; if not found returns the specified value (default=None).

me = {'name': 'Alice'}

print(f"Name: {me.get('name')}")

# When a value is not provided
print(f"Country: {me.get('country')}")

# With specified value
print(f"Country: {me.get('country', 'Taiwan')}")

Output

Name: Alice
Country: None
Country: Taiwan

Merging one Dictionary into Another

Adds new items or modify existing ones.

d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
d1.update(d2)
print(d1)

Output

{'a': 1, 'b': 3, 'c': 4}

Updating Nested Dictionary

Nested Dictionary

data = {
    'l': [1, 2, 3],
    'd': {
        'x': 0, 
        'y': 0
    }
}

data['d']['y'] = 1
data['d']['z'] = 0
print(data)

Output

{'l': [1, 2, 3], 'd': {'x': 0, 'y': 1, 'z': 0}}

Reference