Cheat sheet: list and dictionary operations
This table shows key operations for lists and dictionaries:
Operation | For list L |
For dictionary D |
Notes |
---|---|---|---|
check # of items | len(L) |
len(D) |
Dictionaries have exactly one value per key. |
add an item | L.append(item) , or L.insert(index, item) |
D[key] = value |
Dictionary requires both a key and a value. |
replace an item | L[index] = value |
D[key] = value |
Same syntax as creating a new key for a dictionary. |
remove an item | L.pop(index) |
D.pop(key) |
Pop without argument works for lists (removes last item) but not dicts. |
check presence of an item | item in L |
key in D |
To check for a value in a dictionary, use value in D.values() |
retrieve an item | x = L[index] |
x = D[key] , or x = D.get(key) |
.get will return None if the key is missing instead of causing a KeyError . |
index loop |
|
|
Order of a dictionary is based on the order in which keys were added. |
value loop |
|
|
There's no good way to retrieve the key based on a dictionary value. If you need the key, use an index loop instead. |
Table of Contents
- Lab 10 Home
- Cheat Sheet: Lists & Dictionaries
- Part 1: Exercises
- Part 2: Ironman data
- Knowledge Check