Craig
Craig

Reputation: 843

Check if a dictionary has any key beyond a certain key (i.e., 1+ keys, not counting a particular key)

Subject should say most. Here's an example:

Suppose I want to know if a given dictionary has any keys, but not counting the key 'one'. So

dict = {'one': 1, 'two':2, 'three':3} 

would return TRUE

dict = {'one':1}

would return FALSE

dict = {'two': 2} 

would return TRUE

Upvotes: 0

Views: 59

Answers (3)

jeromej
jeromej

Reputation: 11616

So here is my solution:

if len(mydict) - ('one' in mydict):
    # Your code here

With this:

mydict = {'one': 1, 'two':2, 'three':3}  # Will return 3 - 1 which is True

mydict = {'one':1}  # Will return 1 - 1 which is False

mydict = {'two': 2}  # Will return 1 - 0 which is True

Basically, it will always return the actual length, minus one if 'one' (or anything else you fancy for that matter) is in the list.

An alternative solution:

if len([x for x in mydict if x != 'one']):  # Filters out 'one' if present
    # Your code here

Should work pretty well too. I didn't do any benchmarks to compare both solutions though.

Upvotes: 1

lvc
lvc

Reputation: 35089

dict.viewkeys gives you all the keys in a form that behaves like a set (its a backport of how dict.keys behaves in python 3). This means you can do this as a set difference:

if mydict.viewkeys() - {'one'}:
    # has other keys

Upvotes: 3

BrenBarn
BrenBarn

Reputation: 251458

You can do it more or less as your question title suggests: check if it has more than one key, or doesn't have 'one' as one of its keys:

 if len(myDict) > 1 or (len(myDict)==1 and 'one' not in myDict):

Upvotes: 4

Related Questions