-4

I have this dictionary

score_dict = \
{5: ['Far above average', 'Extremely well', 'Extremely effective', 'Extremely fast', 'Always', 'Strongly agree', 'Far exceeds expectations'],
 4: ['Somewhat above average', 'Very well', 'Very effective', 'Somewhat fast', 'Most of the time', 'Somewhat agree', 'Exceeds expectations'],
 3: ['Average', 'Moderately well', 'Moderately effective', 'Average', 'About half the time', 'Neither agree nor disagree', 'Equals expectations'],
 2: ['Somewhat Below Average', 'Slightly well', 'Slightly effective', 'Somewhat slow', 'Sometimes', 'Somewhat disagree', 'Short of expectations'],
 1: ['Far Below Average', 'Not well at all', 'Not effective at all', 'Extremely slow', 'Never', 'Strongly disagree', 'Far short of expectations'],
}

Why does this not print True?

if 'Far above average' in score_dict.values():
    print("True")
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
justanewb
  • 133
  • 4
  • 15
  • 2
    Because `score_dict.values()` produces a list of lists not a single list. – Mark Aug 27 '21 at 22:58
  • @Mark How would I perform this operation then assuming I do not know the exact key? – justanewb Aug 27 '21 at 22:59
  • Does this answer your question? [Find if value exists in multiple lists](https://stackoverflow.com/questions/34783084/find-if-value-exists-in-multiple-lists) (better use this one: https://stackoverflow.com/questions/40621370/how-can-i-check-if-a-variable-exists-in-multiple-lists) – mkrieger1 Aug 27 '21 at 23:00
  • Do you know how to check whether the string is in an individual list? Do you know how to get all the values from a dictionary? Do you know how to iterate over them? – Karl Knechtel Aug 27 '21 at 23:05

2 Answers2

1

This doesn't print true, because the items in .values() are lists.

One way to do this would be the following:

for l in score_dict.values():
    if 'Far above average' in l:
        print("True")
HPringles
  • 1,042
  • 6
  • 15
1

You can flatten your inner lists so that in compares based on strings, not lists. Here's a minimal example of the problem:

>>> {'a': 'b'}.values()
dict_values(['b'])
>>> 'b' in {'a': 'b'}.values()
True
>>> 'b' in {'a': ['b']}.values() # this is what your structure looks like
False

And a solution:

>>> 'Far above average' in (y for x in score_dict.values() for y in x)
True

If you want the associated key:

>>> for k, v in score_dict.items():
...     if 'Far above average' in v: print(k)
...
5
ggorlen
  • 44,755
  • 7
  • 76
  • 106