In Python, you can safely use a trailing comma in dictionaries (and other collections like lists, tuples, and sets).
my_dict = {
"x": 10,
"y": 20,
}
In Python, dictionary keys have some important rules and behaviors.
animals = {
'a': 'ape',
'b': 'bear',
'c': 'cat',
}
animals.keys()
Output: dict_keys(['a', 'b', 'c'])
animals.values()
Output: dict_values(['ape', 'bear', 'cat'])
list(animals.keys())
Output: ['a', 'b', 'c']
animals.get('a')
Output: 'ape'
animals = {
'a': ['ape', 'abalone'],
'b': ['bear'],
}
Each key (
'a', 'b') maps to a list of values.This means you can store multiple animals under the same starting letter.
animals['b'].append('bat')
You’re accessing the list stored under key
'b' → currently ['bear'].
.append('bat') adds 'bat' to that list..append() modifies the list in place (it doesn’t return a new list).if 'c' not in animals:
animals['c'] = []
animals['c'].append('cat')
Check if key
'c' exists
if 'c' not in animals: → looks for 'c' in the dictionary keys.If
'c' is missing, it creates a new entry with an empty listAppend
'cat' to the listNow
animals['c'] is an empty list [].
.append('cat') adds 'cat' to that list.defaultdict is a special type of dictionary from Python’s collections module. It works just like a normal dictionary, but with one big advantage: if you try to access a key that doesn’t exist, it automatically creates it with a default value instead of raising a KeyError.from collections import defaultdict
>>> animals = defaultdict(list)
>>> animals
Output:
defaultdict(<class 'list'>, {})
This is the string representation (
__repr__) of a defaultdict object.Inside the angular brackets
< >, Python is showing you the default factory function used to create missing values.
<class 'list'> means: whenever you access a missing key, Python will automatically create a new empty list for it.The
{} part after the comma is the current contents of the dictionary (empty at the moment).})
So the whole thing reads as, “This is a defaultdict whose default factory is the list class, and right now it contains an empty dictionary.”
Microsoft Copilot
沒有留言:
發佈留言