Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with Python under the Creative Commons license and many other sources.
Example Dictionary:
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}values():
spam = {'color': 'red', 'age': 42}
for v in spam.values():
print(v)keys():
for k in spam.keys():
print(k)items():
for i in spam.items():
print(i)Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively.
spam = {'color': 'red', 'age': 42}
for k, v in spam.items():
print('Key: {} Value: {}'.format(k, str(v)))spam = {'name': 'Zophie', 'age': 7}
'name' in spam.keys()'Zophie' in spam.values()# You can omit the call to keys() when checking for a key
'color' in spam'color' not in spam'color' in spampicnic_items = {'apples': 5, 'cups': 2}
'I am bringing {} cups.'.format(str(picnic_items.get('cups', 0)))'I am bringing {} eggs.'.format(str(picnic_items.get('eggs', 0)))Let's consider this code:
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'Using setdefault we could make the same code more shortly:
spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black')spamspam.setdefault('color', 'white')spamimport pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)# in Python 3.5+:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
z