user1692333
user1692333

Reputation: 2597

How to check if all specifiedn keys exist in array?

For example I have something like this:

{'key1': 'value', 'key2': 'value', 'key3': 'value','key4': 'value','key4': 'value'}

And have an array:

['key1', 'key3']

How to check if all keys from second array exists in first?

Upvotes: 1

Views: 95

Answers (4)

dragon2fly
dragon2fly

Reputation: 2419

You can use set.issubset() method to check

a = {'key1': 'value', 'key2': 'value', 'key3': 'value','key4': 'value','key4': 'value'}
b = ['key1', 'key3']

set(b).issubset(a)
#True

c = ['key1', 'key5']
set(c).issubset(a)
#False

Edit: apply issubset directly on a according to @Maroun Maroun comment

Upvotes: 3

Maroun
Maroun

Reputation: 95958

Another way (using set and issubset):

set(['key1', 'key3']).issubset(your_dict)

Upvotes: 1

lqhcpsgbl
lqhcpsgbl

Reputation: 3782

Use a loop and in operator with dict object:

adict = {'key1': 'value', 'key2': 'value', 'key3': 'value','key4': 'value','key4': 'value'}

keys_list = ['key1', 'key3']
for key in keys_list:
  if key in adict:
    print key

"in" can check if the key in a dict

Upvotes: 0

Ffisegydd
Ffisegydd

Reputation: 53678

You can use all and a generator expression. This will iterate over your array and check that each key is in the keys of d. If at least one of the keys is missing then it'll return False.

d = {'key1': 'value', 'key2': 'value', 'key3': 'value','key4': 'value','key4': 'value'}
a = ['key1', 'key3']

all(key in d for key in a) # True

a2 = ['key1', 'key5']

all(key in d for key in a2) # False

Upvotes: 7

Related Questions