Reputation:
How to check that all the keys and their values are same in dictionary? what would be the fastest way to acheve this?
{2: 2, 4: 2, 1: 1} #print false
{4: 4, 2: 2, 1: 1} # print true
Upvotes: 0
Views: 170
Reputation: 41
all(key==value for key,value in d.items())
all is special function in python , which will retrun True only if all the elements satisfy the condition,
Upvotes: 0
Reputation: 2665
Using Xor
to compare each value.
result = True if sum([d[i] ^ i for i in d]) == 0 else False
Edited to remove redundancies:
result = sum([d[i] ^ i for i in d]) == 0
Upvotes: 0
Reputation: 1540
One-liner:
print(True) if list(d.keys())==list(d.values()) else print(False)
Upvotes: 0
Reputation: 333
try this
for k, v in dictionary.items():
if k != v:
return false
return true
Upvotes: 0
Reputation: 439
you can use comprehension
print(False) if any([item1!=item2 for item1, item2 in dict.items()]) else print(True)
Upvotes: 0
Reputation: 82765
Using all
Ex:
data = [{2: 2, 4: 2, 1: 1}, {4: 4, 2: 2, 1: 1}]
for i in data:
if all(k==v for k,v in i.items()):
print(True)
else:
print(False)
Output:
False
True
Upvotes: 3