Skip to content
Advertisement

How to loop through values in a dictionary to see if they ever appear as a key

I have the following dictionary (i.e., my_dict). Basically each key is a sick person and the values for that key are the people they have been in contact with. I need the people that occur only in the values and never in the keys. Philip and Sarai are the only names that appear as values but not keys.

This is the code I have tried so far. How can I change it to effectively loop through the values to determine if they ever appear as a key?

my_dict = {'Bob': ['Paul', 'Mark', 'Carol', 'Leanne', 'Will'],
           'Carol': ['Mark', 'Leanne'],
           'Farley': ['Paul'],
           'Leanne': ['Sarai'],
           'Larry': ['Carol', 'Mark', 'Leanne', 'Will'],
           'Mark': ['Philip', 'Zach'],
           'Paul': ['Zach'],
           'Will': ['Leanne', 'Mark'],
           'Zach': ['Philip']}

list = []
for key in my_dict:
    variable = True
    for value in my_dict.values():
        if key in value:
            variable = False
    if variable == True:
        list.append(value)

print(list)

Advertisement

Answer

You can do what you want in a fairly straight-forward, readable, and efficient manner, as shown below. I made only_values a set to prevent duplicates as you requested in a comment.

my_dict = {'Bob': ['Paul', 'Mark', 'Carol', 'Leanne', 'Will'],
           'Carol': ['Mark', 'Leanne'],
           'Farley': ['Paul'],
           'Leanne': ['Sarai'],
           'Larry': ['Carol', 'Mark', 'Leanne', 'Will'],
           'Mark': ['Philip', 'Zach'],
           'Paul': ['Zach'],
           'Will': ['Leanne', 'Mark'],
           'Zach': ['Philip']}

only_values = {person for people in my_dict.values()
                          for person in people
                              if person not in my_dict}

print(only_values)  # -> {'Philip', 'Sarai'}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement