Skip to content

Instantly share code, notes, and snippets.

Embed
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
@navyad

This comment has been minimized.

Copy link
Owner Author

commented May 24, 2018

In [7]: dic = {"name": "nav", "email": "nav@gmail.com"}

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

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

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

In [11]: ee['a']
Out[11]:

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.