Python Notes
I don’t really know what I am going to do on this page. But I have some notes about the Python standard library that I want to save for my future self.
.islower() (and .isupper())
Return True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.
Cased characters are those with the Unicode general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase). This means that the method checks for characters that are specifically recognized as letters in their uppercase, lowercase, or titlecase forms.
print('a'.islower()) # True
print('A'.islower()) # False
print('1'.islower()) # False
print('a1'.islower()) # True
print('á'.islower()) # True
print('Á'.islower()) # False
print('汉'.islower()) # False # Chinese character, not cased
print('ß'.islower()) # True # German sharp s, considered lowercase
See more:
Dictionary Ordering
As of Python 3.6 in CPython and 3.7 in all implementations ↗, dictionaries are iterated in the insertion order of keys.
d = {}
d[1] = True
d[2] = True
d[3] = True
print(d) # {1: True, 2: True, 3: True}
d[2] = False
print(d) # {1: True, 2: False, 3: True}
del d[2]
d[2] = True
print(d) # {1: True, 3: True, 2: True}
OrderedDict
OrderedDict can be used if you want to explicitly state the importance of the order or if you want to use methods like .move_to_end() or .popitem().
See more:
- Real Python: OrderedDict vs dict in Python: The Right Tool for the Job
- Python Documentation: collections.OrderedDict
- Python Documentation: dict
Default Value for max() (and min())
If max() is given an sequence, it will raise a ValueError. As of Python 3.4, the max() function supports a default parameter, which is returned if the provided sequence is empty.
This is helpful when dealing with sequences of unknown length that could be empty.
print(max([], default=0)) # 0
See more:
Get Python Version
import sys
print(sys.version) # '3.9.6 (default, Jul 27 2021, 07:03:06) [GCC 8.3.0]'
See more:
dict.get()
The dict.get() method is a safe way to retrieve values from a dictionary without raising a KeyError if the key doesn’t exist.
dict.get(key, default=None)
This method returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
d = {'a': 1, 'b': 2}
print(d.get('a')) # 1
print(d.get('c')) # None
print(d.get('c', 0)) # 0
# Contrast with direct key access:
print(d['a']) # 1
# print(d['c']) # Raises KeyError
Useful when you want to handle missing keys without using a try-except block.
See more: