Manolo Dominguez Becerra
Manolo Dominguez Becerra

Reputation: 1357

How to iterate over the elements in lists in the values of a dictionary

I want to assert if all values in lists in the values of a dict are integer.

My dictionary is very long and I don't know an efficient way to do this.

My dictionary looks like this:

{'chr7': [[127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864], [127475864, 127477031], [127477031, 127478198], [127478198, 127479365], [127479365, 127480532]], 'chr8': [[127480532, 127481699], [127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864]], 'chr9': [[127475864, 127477031], [127477031, 127478198], [127478198, 127479365], [127479365, 127480532], [127480532, 127481699]], 'chrX': [[127480532, 127481699]], 'chr1': [[127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864], [127475864, 127477031], [127477031, 127478198], [127478198, 127479365], [127479365, 127480532]], 'chr2': [[127480532, 127481699], [127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864]], 'chr3': [[127475864, 127477031], [127477031, 127478198]], 'chr4': [[127478198, 127479365], [127479365, 127480532], [127480532, 127481699]], 'chrY': [[127480532, 127481699]]}

I have been trying something like this

assert all(isinstance(value, list) and all(isinstance(el, int) 
        for el in value)for value in bed_data.values()), "Values of the dictionnary aren't lists of integers"

(Code copy from here Assert data type of the values of a dict when they are in a list)

Upvotes: 0

Views: 66

Answers (2)

Corralien
Corralien

Reputation: 120409

You don't need to try all items. Stop at the first failed test (not an instance of int) and prefer use TypeError rather than AssertionError:

import itertools

for l in bed_data.values():
    for v in itertools.chain.from_iterable(l):
        if not isinstance(v, int):
            raise TypeError(f"Values of the dictionnary aren't lists of integers '{v}'")

Upvotes: 1

mozway
mozway

Reputation: 260640

You could use a generator:

assert all(isinstance(e, int)
           for l1 in bed_data.values()
           for l2 in l1 for e in l2)

It will raise an AssertionError for the first invalid value. If all values are correct, there is no choice but to test them all.

Upvotes: 1

Related Questions