0

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

  • It does not look like a regex question, you are checking if a string equals some value. Also, your keys are numbers, there are no letters. – Wiktor Stribiżew Nov 23 '21 at 12:52

4 Answers4

2

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 {key}.")
riquefr
  • 260
  • 1
  • 7
0

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}")
Kris
  • 8,680
  • 4
  • 39
  • 67
0
d = {128: ['S', 'S', 'O', 'F'], 512: ['S', 'F']}

for key in d:
  if not (d[key].count('F') == 1 and d[key].count('S') == 1):
    print(f"There is no start or end stop for the line {key}.")
sogand
  • 1
  • This appears to be an exact duplicate of the code from [@riquefr's answer](https://stackoverflow.com/a/70081334/3025856), posted a couple days ago, except that you included less explanation. Please review existing answers before contributing a new one. It is nice that you included sample data, but the function itself appears to be an exact copy. If I'm missing something, others will too: In that case, edit your answer to explain what differentiates your approach. – Jeremy Caney Nov 26 '21 at 01:05
-1

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})}
dawg
  • 98,345
  • 23
  • 131
  • 206