Skip to content

Commit

Permalink
add setting a default value to a dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyguitar committed May 16, 2019
1 parent 67d7c2c commit ded88e9
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions docs/notes/python-dict.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,51 @@ Find Same Keys
['3', '2']
[('1', 1), ('3', 3), ('2', 2)]
Set a Default Value
-------------------

.. code-block:: python
# intuitive but not recommend
>>> d = {}
>>> key = "foo"
>>> if key not in d:
... d[key] = []
...
# using d.setdefault(key[, default])
>>> d = {}
>>> key = "foo"
>>> d.setdefault(key, [])
[]
>>> d[key] = 'bar'
>>> d
{'foo': 'bar'}
# using collections.defaultdict
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["key"]
[]
>>> d["foo"]
[]
>>> d["foo"].append("bar")
>>> d
defaultdict(<class 'list'>, {'key': [], 'foo': ['bar']})
``dict.setdefault(key[, default])`` returns its default value if *key* is not in
the dictionary. However, if the key exists in the dictionary, the function will
return its value.

.. code-block:: python
>>> d = {}
>>> d.setdefault("key", [])
[]
>>> d["key"] = "bar"
>>> d.setdefault("key", [])
'bar'
Update Dictionary
-----------------

Expand Down

0 comments on commit ded88e9

Please sign in to comment.