@extends('template') @section('title') Cheat sheet: list and dictionary operations @stop @section('content') # 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
for i in range(len(L)):
    ...
for key in D:
    ...
Order of a dictionary is based on the order in which keys were added.
value loop
for item in L:
    ...
for value in D.values():
    ...
There's no good way to retrieve the key based on a dictionary value. If you need the key, use an index loop instead.
@include('/labs/lab10/_toc') @stop