LoginSignup
3
3

More than 5 years have passed since last update.

Python / dictionary > setdefault() > 辞書になかったら追加する

Last updated at Posted at 2017-04-18

@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic
(No. 3118 / 12833)
Handle Missing Keys with setdefault() and defaultdict()

The setdefault() function is like get(), but also assigns an item to the dictionary if the key is missing:

試してみた。

away_team = { 'Tuvok': 1, "B'Elanna" : 2 }
print(away_team)
seven = away_team.setdefault("7of9", 3)
print(away_team)
print(seven)
run
{"B'Elanna": 2, 'Tuvok': 1}
{"B'Elanna": 2, 'Tuvok': 1, '7of9': 3}
3
3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3