Anna
Anna

Reputation: 974

By checking the element type in a list, returns wrong value

There are 2 lists, one with dict inside and snother with int

values_dict = [{'other clicks': 497, 'photo view': 509, 'link clicks': 49}]

values_int = [1055]

I have to first check the type of element inside and then make something else

So, the most easy way:

for v in values_dict:
    if type(v) == dict:
        print('1')
    elif type(v) != dict:
        print('2')

I have no idea why, but it returns '2', like there is not a dict inside values_dict variable.

However,

for v in values_dict:
    print(type(v))

Returns <class 'dict'>

I have tried like this

for v in values_dict:
    if isinstance(value, type(dict)) is True:
        print('1')
    else:
        print('2')

It also returns '2'

I have no idea what is wrong, has somebody experienced the same issue?

Upvotes: 0

Views: 574

Answers (1)

CDJB
CDJB

Reputation: 14546

This should work - your second code was off slightly. The documentation for type() can be seen here, and recommends using isinstance() for testing the type of an object. The return value of type is a type object - not a string, so testing the value of it against a string often yields unexpected results.

for v in values_dict:
    if isinstance(v, dict):
        print('1')
    else:
        print('2')

Output:

1

Upvotes: 2

Related Questions