Reputation: 976
I have list of dictionaries and in each one of them the key site
exists.
So in other words, this code returns True
:
all('site' in site for site in summary)
Question is, what will be the pythonic way to iterate over the list of dictionaries and return True
if a key different from site
exists in any of the dictionaries?
Example: in the following list I would like to return True
because of the existence of cost
in the last dictionary BUT, I can't tell what will be the other key, it can be cost
as in the example and it can be other strings; random keys for that matter.
[
{"site": "site_A"},
{"site": "site_B"},
{"site": "site_C", "cost": 1000}
]
Upvotes: 1
Views: 46
Reputation: 27879
This is a bit longer version, but it gives you what you need. Just to give more options:
any({k: v for k, v in site.items() if k != 'site'} for site in summary)
Upvotes: 0
Reputation: 4716
You could just check, for each dictionary dct
:
any(key != "site" for key in dct)
If you want to check this for a list of dictionaries dcts
, shove another any
around that: any(any(key != "site" for key in dct) for dct in dcts)
This also makes it easily extensible to allowing multiple different keys. (E.g. any(key not in ("site", "otherkey") for key in dct)
) Because what's a dictionary good for if you can only use one key?
Upvotes: 2
Reputation: 1122262
If all dictionaries have the key site
, the dictionaries have a length of at least 1. The presence of any other key would increase the dictionary size to be greater than 1, test for that:
any(len(d) > 1 for d in summary)
Upvotes: 7