Getting the difference between two dates or datetime objects in python is delightfully straightforward; you can just subtract them! For date objects The subtraction returns an object of class timedelta, which has a few handy properties like .seconds and .days. If using whole date objects however, only the .days property will matter. Since there’s no […]
Python
Reading CSVs in Python
When reading in CSVs in Python, you have two main options: Let’s go through an example of each using a spreadsheet containing some US political funding data I have around from a personal project. Option 1: Python’s csv module: That’s it! Now you have access to the data in a list of dicts. You might […]
Python Context Managers: the “with” Statement
When reading and writing files in python, you’ll often see the use of with: This is called a Python context manager, and it’s essentially an automatic way to clean up after yourself. The code block above is functionally equivalent to this block: Without a context manager, we have to remember to manually .close() the file, […]
Swapping dict keys and values in Python
Sometimes you need to invert the keys and values in a dictionary. Fortunately, Python gives us a concise way to do exactly that with list comprehensions and dict.items(): However, if you have nested dictionaries this method won’t work: This error is caused by attempting to use the entire “address” dict as a key in the […]
Merging Python Dictionaries
Merging dictionaries in Python is a common task, and there are a few ways to do it: The unpacking operator ** Since Python 3.5 (circa 2015), the simplest way to merge dictionaries has been with Python’s unpacking operator ** : It’s worth noting that if the objects being merged share a key, the last one […]