Home > Net >  How to skip missing items in a loop
How to skip missing items in a loop

Time:12-02

I have a dictionary

dictionary = {'Mon':['Mary','Suszie','Larry'],
              'Tue':['Sam','Ola','Chris'],
              'Wed':['Tanner','Ram','Dustin']}

I am using this dictionary to generate plots from a larger datasets. If I call the key 'Mon' and let's say the value 'Larry' isn't present in my dataset, my loop fails at 'Larry' with an error. How can I make my loop skip missing items?

Code example:

dataset = {'Mary':[1,4,6,2,7],
           'Suszie':[9,2,6,4,7],
           'Max':[1,3,1,3,5]}

for x in dictionary.values():
    for z in datasets.keys():
        if x not in z:
           continue
             plt.plot(z)

CodePudding user response:

You almost got it:

for x in dictionary.values():
    for v in x:
        if v not in dataset:
           continue
        plt.plot(dataset[v])

CodePudding user response:

dataset.keys() is a set-like object, including support for things like &:

for names in dictionary.values():
    for z in dataset.keys() & names:
        plt.plot(dataset[z])

The dict_keys object must be on the left; the right-hand operand of dict_keys.__and__ can be any iterable value.

CodePudding user response:

dictionary is a structure that is hard to work with: it is a dictionary where the values are list of names. It would be simpler to convert this dictionary into a simple set of names.

import itertools
all_persons = set(itertools.chain(*dictionary.values()))
# all_persons is
# {'Mary', 'Larry', 'Ola', 'Tanner', 'Suszie', 'Dustin', 'Ram', 'Sam', 'Chris'}

for person in dataset.keys() & all_persons:
    plt.plot(dataset[person])

In the code above, I converted dictionary from a dictionary to all_person, which is a set of person names. From there, the loop would be simple and we don't need any if statement at all.

  • Related