Dictionary

Mutable, unordered pairs (keys and values) of objects. Keys must be hashable.

Advantages: O(1) searching for keys. Makes it easy to create trees and other hierarchical data structures. Can be used to create self-documenting code. Many problems can be described in terms of key-value pairs.

Disadvantages: Only lookup by key. Uses more memory than lists and tuples. Keys must be hashable.

Creating

{'a':1, 'b':2, 'c':3}      # {'a': 1, 'b': 2, 'c': 3}

Creating from other type

dict(['a',1], ['b',2], ['c',3])      # {'a': 1, 'b': 2, 'c': 3}
dict(('a',1), ('b',2), ('c',3))      # {'a': 1, 'b': 2, 'c': 3}

Retrieving from a key

# 1st way
d = {'a':1, 'b':2, 'c':3}
d['a']         # 1
d['z']         # raises KeyError

# 2nd way
d = {'a':1, 'b':2, 'c':3}
d.get('a')     # 1

Add a key-value pair

d = {'a':1, 'b':2, 'c':3}
d['d'] = 100
d              # {'a': 100, 'b': 2, 'c': 3, 'd': 100}

Replacing an existing value

Replacing multiple existing values

Removing an element

Getting the keys

Getting the values

Iterating over the keys

Iterating over the pairs

Iterating over the sorted keys

Find the key with max/min value

Check membership

Update frequency

Last updated

Was this helpful?