user13294293
user13294293

Reputation:

How to check condition in dictionary?

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

Answers (7)

Tomfus
Tomfus

Reputation: 83

Try this:

all(dict[key]==key for key in dict)

Upvotes: 0

Muthuraj
Muthuraj

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

TheLazyScripter
TheLazyScripter

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

Strange
Strange

Reputation: 1540

One-liner:

print(True) if list(d.keys())==list(d.values()) else print(False)

Upvotes: 0

rn0mandap
rn0mandap

Reputation: 333

try this

for k, v in dictionary.items():
    if k != v:
        return false
    return true

Upvotes: 0

Michael Hsi
Michael Hsi

Reputation: 439

you can use comprehension

print(False) if any([item1!=item2 for item1, item2 in dict.items()]) else print(True)

Upvotes: 0

Rakesh
Rakesh

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

Related Questions