-2

For example, if a dictionary is defined pythonDict = {a: 1, b: 2} and it is referenced pythonDict["c"] or pythonDict["d"], can the dictionary be defined a default value for any key that isn't listed, without listing all the possibilities?

I'd like to have a reference in one line without an additional "if" statement to check if the key is included.

iceburger
  • 99
  • 2

2 Answers2

0

Use a defaultdict

>>> from collections import defaultdict
>>> pythonDict = defaultdict(lambda: 100, a=1, b=2)
>>> pythonDict["c"]
100
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
-2

Use dict.get(key, default value). It returns value when key is in dict. Otherwise, it returns default value.

Example code.

dic = {"a":1, "b":2}
my_default = "default"
print(dic.get("a", my_default))
print(dic.get("c", my_default))
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11