Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
default values without KeyError
In [1]: from collections import defaultdict
In [2]: dd = defaultdict(lambda: 100, a=22, b=11)
In [3]: dd
Out[3]: defaultdict(<function __main__.<lambda>>, {'a': 22, 'b': 11})
In [4]: dd.update({"c": 33})
In [5]: dd
Out[5]: defaultdict(<function __main__.<lambda>>, {'a': 22, 'b': 11, 'c': 33})
In [6]: dd['d']
Out[6]: 100

This comment has been minimized.

Copy link
Owner Author

navyad commented May 24, 2018

In [7]: dic = {"name": "nav", "email": ""}

In [8]: ee = defaultdict(lambda: None, **dic)

In [9]: ee
defaultdict(<function main.>,
{'email': '', 'name': 'nav'})

In [10]: ee['name']
Out[10]: 'nav'

In [11]: ee['a']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.