杰瑞科技汇

Python getdefault(),如何使用与区别?

Of course! In Python, "getdefault" isn't a built-in function, but it's a very common pattern. The most likely function you're looking for is dict.get(), which provides a way to safely get a value from a dictionary.

Python getdefault(),如何使用与区别?-图1
(图片来源网络,侵删)

I'll cover the main getdefault-like methods, starting with the most common one.


The Main Answer: dict.get() for Dictionaries

The dict.get() method is the standard way to get a value from a dictionary if the key exists, and return a default value if it doesn't. This prevents a KeyError that would occur with a standard dictionary lookup using square brackets [].

Syntax

dictionary.get(key, default_value)
  • key: The key you are looking for in the dictionary.
  • default_value: (Optional) The value to return if the key is not found. If you don't provide a default, it returns None.

Example

Let's say you have a dictionary of user settings.

user_settings = {
    'theme': 'dark',
    'font_size': 14,
    'notifications': True
}
# --- Using the square bracket notation (can cause an error) ---
# print(user_settings['language'])  # This would raise a KeyError!
# --- Using .get() to safely retrieve a value ---
# Case 1: Key exists
theme = user_settings.get('theme')
print(f"The theme is: {theme}")  # Output: The theme is: dark
# Case 2: Key does NOT exist, and we provide a default
language = user_settings.get('language', 'en-US')
print(f"The language is: {language}")  # Output: The language is: en-US
# Case 3: Key does NOT exist, and no default is provided
show_welcome = user_settings.get('show_welcome_screen')
print(f"Show welcome screen? {show_welcome}")  # Output: Show welcome screen? None

This is the most direct and Pythonic way to handle "get a value or default" for dictionaries.

Python getdefault(),如何使用与区别?-图2
(图片来源网络,侵删)

collections.defaultdict for "Smart" Default Values

Sometimes, you don't just want to return a static default value (like 0 or 'N/A'). You want to create a default value when a key is first accessed. For this, you use collections.defaultdict.

A defaultdict is a subclass of dict that calls a factory function to supply missing values.

Syntax

from collections import defaultdict
defaultdict(factory_function)

The factory_function is just a function that returns the default value you want. Common ones are int (for 0), list (for []), or str (for ).

Example

Imagine you want to count the frequency of words in a sentence. Using a normal dict, you'd have to check if a key exists first. With defaultdict, it's much cleaner.

Python getdefault(),如何使用与区别?-图3
(图片来源网络,侵删)
from collections import defaultdict
text = "the quick brown fox jumps over the lazy dog the fox"
word_counts = defaultdict(int) # int() returns 0
for word in text.split():
    word_counts[word] += 1
print(word_counts)
# Output: defaultdict(<class 'int'>, {'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1})
# Accessing a key that doesn't exist automatically creates it with the default value
print(f"Count of 'cat': {word_counts['cat']}") # Output: Count of 'cat': 0

Another common use is for grouping items.

from collections import defaultdict
students = [
    {'name': 'Alice', 'grade': 'A'},
    {'name': 'Bob', 'grade': 'C'},
    {'name': 'Charlie', 'grade': 'A'},
    {'name': 'David', 'grade': 'B'},
]
# Group students by their grade
grade_groups = defaultdict(list)
for student in students:
    grade_groups[student['grade']].append(student['name'])
print(grade_groups)
# Output:
# defaultdict(<class 'list'>, {'A': ['Alice', 'Charlie'], 'C': ['Bob'], 'B': ['David']})

dict.setdefault() for Setting and Getting

This is a slightly different but related method. setdefault() checks if a key exists. If it does, it returns its value. If it does not, it inserts the key into the dictionary with the specified default value and then returns that value.

Syntax

dictionary.setdefault(key, default_value)

Example

This is useful when you want to ensure a key exists with a default value (like an empty list) before you modify it.

user_data = {
    'username': 'jane_doe',
    'posts': []
}
# Let's add a new post to the user's list of posts.
# We need to make sure the 'posts' key exists and is a list.
# Using .setdefault() is a clean way to do this
user_data.setdefault('posts', []).append('My first post!')
user_data.setdefault('comments', []).append('Hello world!')
print(user_data)
# Output:
# {
#     'username': 'jane_doe',
#     'posts': ['My first post!'],
#     'comments': ['Hello world!']
# }

Compare this to the more verbose way without setdefault:

if 'posts' not in user_data:
    user_data['posts'] = []
user_data['posts'].append('My first post!')

setdefault achieves the same thing in one line.


Summary: Which one should you use?

Method When to Use Example
dict.get(key, default) Most common. You need to get a value if a key exists, otherwise return a specific default value. config.get('port', 8080)
collections.defaultdict You need a default value that is created on the fly (e.g., 0, [], ) for new keys. word_counts = defaultdict(int)
dict.setdefault(key, default) You need to get a value, but if the key is missing, you also want to set it to the default value first. user.setdefault('settings', {})

For most "get a default" scenarios, dict.get() is the one you're looking for.

分享:
扫描分享到社交APP
上一篇
下一篇