Home > Mobile >  In a dictionnary, how to check that a key has exactly 1 value?
In a dictionnary, how to check that a key has exactly 1 value?

Time:11-23

I have this dictionnary:

{128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}

I would like to be sure that each key has exactly one value 'F' and one value 'S' and return a message if it's not the case

I tried this but it didn't seem to work: it didn't print the message

for key in d:
    if not re.search(r"[F]{1}","".join(d[key])) or not re.search(r"[S].{1}","".join(d[key])):
        print(f"There is no start or end stop for the line {key}.")

Thanks

CodePudding user response:

Your dictionary contain a list, not a string so you shouldn't use regex. You can check if the list contain exactly the number of values you want using list.count(value).

for key in d:
  if not (d[ḱey].count('F') == 1 and d[ḱey].count('S') == 1):
    print(f"There is no start or end stop for the line {i}.")

CodePudding user response:

You can check the count of those characters in each value. One approach is below

sample = {128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}
wrong_lines = [index for index, value in sample.items() if value.count('S') == value.count('F') == 1]
print(f"Wrong lines {wrong_lines}")

CodePudding user response:

You can use a Counter and get the counts of all letters simultaneously:

>>> from collections import Counter
>>> di={128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}
>>> {k:Counter(v) for k,v in di.items()}
{128: Counter({'S': 2, 'O': 1, 'F': 1}), 512: Counter({'S': 1, 'F': 1})}
  • Related