Keys in dict and keys not in dict

Peter Otten __peter__ at web.de
Mon Mar 19 03:09:39 EDT 2018


Ben Finney wrote:
> Chris Angelico <rosuav at gmail.com> writes:
>>> Sounds like a set operation to me.
>>>> expected = {"foo", "bar", "spam"}
>> missing = expected - set(json)
>> That works (because iterating a dict returns its keys). But it is less
> immediately understandable, IMO, than this::
>> expected = {"foo", "bar", "spam"}
> missing = expected - set(json.keys())

There's no need to materialize the set of keys: 
>>> expected = {"foo", "bar", "ham"}
>>> json = dict(foo=1, bar=2, spam=3)
>>> expected - json.keys()
{'ham'}
In Python 2 use json.viewkeys() instead of keys().


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /