Python Dict Examples

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Filter dict keys

Return the items as a list of tuples then build a new dict.

allowed_keys = ['bar','baz']

d = {'foo':1,'bar':2}

filtered_items = [(k,v) for (k,v) in d.items() if k in allowed_keys]

dict(filtered_items)
# >> {'bar': 2}

References

Dialogue & Discussion