-
Dictionaries
-
Strings, tuples, ranges, lists
- Common operations
- seq[i]
- len(seq)
- seq1 + seq2 (not ranges)
- n*seq -> sequence that repeats seq n times ( not ranges )
- seq[start:end]
- 3 in seq
- 3 not in seq
for e in seq
-> iterates over elements of sequence- Properties
Only lists are mutable
Dictionaries
- Index item of interest directly (not always int)
- Use one data structure
- A python dictionary { }
- Store pairs of data
- Key : Value
my_dict = {}
grades = {‘John’: ‘A+’, ‘Katy’:’A’}
Operations
- Add an entry:
grades[‘Sylvan’] = ‘B+’
- Remove an entry:
del(grades[‘Ana’])
- Copy a dict:
dict2 = dict(dict1)
or
dict2 = dict1.copy()
- Test if a key is in the dictionary:
‘Daniel’ in grades
- Get an iterable that acts like a tuple of all keys:
grades.keys() # [‘Ana’,’Ben’]
- Get an iterable that acts like a tuple of all values:
grades.values()
- Safe way to access a value if we are not sure the key is in the dictionary:
d.get(key, default)
Keys and Values
Values
- Can be any type (immutable or mutable)
- Can be duplicates
- Can be lists, even other dictionaries
Keys
- Must be unique
- Immutable type(int, float, string, tuple, bool)
- Need an object that is hashable, all immutable types are hashable
- Careful with float type as a key
- No order to keys or values
Examples with a Dictionary
- Fibonacci and dictionaries
-
Recursive fibonacci is ineffective because it keeps recalculating
Store the already-calculated result in a dictionary to save the recalculating