简体   繁体   English

"有没有办法在 Python 的字典中设置默认值?"

[英]Is there a way to have a default value inside a dictionary in Python?

I wnat to know if there is a way to have a default value in a dictionary (without using the get function), so that:我想知道是否有办法在字典中设置默认值(不使用 get 函数),这样:

dict colors = {
"Black":(0, 0, 0),
"White":(255, 255, 255),
default:(100, 100, 100)
};

paint(colors["Blue"]);  # Paints the default value (Grey) onto the screen

You can use a defaultdict<\/code> .您可以使用defaultdict<\/code> 。

from collections import defaultdict

colors = defaultdict(lambda: (100, 100, 100))

colors["Black"] = (0, 0, 0),
colors["White"] = (255, 255, 255)

# Prints (0, 0, 0), because "Black" is mapped to (0, 0, 0) in the dictionary.
print(colors["Black"]) 

# Prints (100, 100, 100), because "Blue" is not a key in the dictionary.
print(d["Blue"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python的字典中访问字典的值 - How to access a value of a dictionary inside dictionary in python 有没有一种方法可以将字典作为python中的熊猫数据框的入口? - Is there a way to have a dictionary as an entry of a pandas Dataframe in python? 如何访问 python 字典中值内的值 - How to access a value inside a value in a python dictionary python:字典获取方法默认值问题 - python: problem with dictionary get method default value 如何在python中使用默认值定义多维字典? - How to define multidimensional dictionary with default value in python? 使用默认值python设置字典的缺失值 - setting the missing values of dictionary with default value python 有没有办法在字典中索引嵌套列表? PYTHON - Is there a way to index a nested list inside a dictionary? PYTHON 如何在具有字典作为值的python中编辑字典值? - how to edit a dictionary value in python that have a dictionary as a value? 有没有办法随机打乱 Python 字典中的键和值,但结果不能有任何原始键值对? - Is there a way to randomly shuffle keys and values in a Python Dictionary, but the result can't have any of the original key value pairs? Python:使用变量键和 append 构建字典作为循环内值的列表的方法 - Python: Way to build a dictionary with a variable key and append to a list as the value inside a loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM