Python: dictionaries, lists and tuples
Python cheat sheet: iterating over a dictionary, listing keys and values, finding a key from its value, sorting numbers stored as strings.
A cheat sheet for dictionaries, lists and tuples in Python.
Dictionaries
Iterating over the key/value pairs of a dictionary:
placard = {"chemise": 3, "pantalon": 6, "tee shirt": 7}
for key, value in placard.items():
print(key, value)
Equivalent form using the tuples returned by items():
for keyvalue in placard.items():
key, value = keyvalue[0], keyvalue[1]
Keys, values and pairs
With d = {'a': 1, 'b': 2, 'c': 3}:
| Expression | Result |
|---|---|
list(d) |
the keys: ['a', 'b', 'c'] |
list(d.keys()) |
the keys: ['a', 'b', 'c'] |
list(d.values()) |
the values: [1, 2, 3] |
list(d.items()) |
(key, value) tuples: [('a', 1), ('b', 2), ('c', 3)] |
Finding a key from its value
mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # george
Lists and tuples
list1 = ['physics', 'chemistry', 1997, 2000]
mon_tuple = (1, "ok", "example")
A list is mutable; a tuple is not.
Sorting
b = ["949.0", "1099.0"]
b.sort(key=float)
print(b) # ['949.0', '1099.0']
key=float sorts the strings by their numeric value. Without it, the sort is alphabetical and "1099.0" would come before "949.0".
Types and attributes
isinstance(t, MyClass) # True if t is an instance of MyClass
issubclass(SubClass, MyClass) # True if SubClass inherits from MyClass
t.__dict__ # attributes of the instance t
dir(t) # attributes and methods of t
Characters and codes
list(map(lambda x: ord(x), "ABC")) # [65, 66, 67]
list(map(chr, [66, 53, 0, 94])) # ['B', '5', '\x00', '^']
ord() returns the Unicode code point of a character; chr() does the reverse.
Notes
list.index()raises aValueErrorif the searched value is not in the list. Testing withinfirst avoids the error.