Skip to content

Latest commit

 

History

History
141 lines (100 loc) · 2.56 KB

File metadata and controls

141 lines (100 loc) · 2.56 KB

Python Cheat Sheet

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.

Read It

Dictionaries and Structuring Data

Example Dictionary:

myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}

The keys, values, and items Methods

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)))

Checking if a Key or Value Exists in a Dictionary

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 spam

The get Method

picnic_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)))

The setdefault Method

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')
spam
spam.setdefault('color', 'white')
spam

Pretty Printing

import 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)

Merge two dictionaries

# in Python 3.5+:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
z