0

I have the following data:

Switch1
int1
int2
int3
int4
Switch2
int1
int2
int3
int4
int5
int6
int7
int8
Switch3
int1
int2
int3
int4
int5
int6
int7

Please help with Python 3 code to count all the items under each of the Switches (Switch1, 2, 3). I do have the list of the Switches in a separate file if that makes it easier.

3
  • If you have any control over the format of your data file it would be wise use YAML. Sep 28, 2018 at 3:22
  • @RedCricket. Why? Sep 28, 2018 at 3:32
  • Go learn about yaml and python that's why import yaml my_dict = yaml.load(open('./datafile.yaml')) for key, value in my_dict.items(): print ( "%s has %s interfaces." % (key, len(my_dict[key]))) Sep 28, 2018 at 3:57

3 Answers 3

2

Assuming that your file content is stored in variable s, you can use re.split with a dict comprehension over an iterator to obtain the counts in a dict indexed by switch names:

import re
i = iter(re.split('(Switch\d+)\n', s)[1:])
print({k: len(v.splitlines()) for k, v in zip(i, i)})

With your sample input, this outputs:

{'Switch1': 4, 'Switch2': 8, 'Switch3': 7}
2

Iterate over the file. Each line will either be a new switch or something to count:

switches = {}
latest = None
with open('data.txt') as f:
    for line in f:
        if line.startswith('Switch'):
            latest = line.strip()
        else:
            switches[latest] = switches.get(latest, 0) + 1

Alternatively, you could use collections.defaultdict instead of get to ensure that the dictionary is populated properly for each new key:

from collections import defaultdict

switches = defaultdict(int)
with open('data.txt') as f:
    for line in f:
        if line.startswith('Switch'):
            latest = line.strip()
        else:
            switches[latest] += 1
5
  • Yeah, this is the solution I would do but with defaultdict int instead.
    – Anton vBR
    Sep 28, 2018 at 3:44
  • 1
    @Anton. That was done in good enough taste that I'll leave it in. Thanks. Sep 28, 2018 at 3:51
  • If the data file was yaml you could simplify your script to [ print ( "%s has %s interfaces." % (key, len(value))) for key, value in yaml.load(open('./datafile.yaml')).items() ] Sep 28, 2018 at 4:07
  • Thank you very much for the defaultdict solution. I have just learned it but did not know how to apply it; I guess perhaps due to the non-programming background. It will take some time to think like a programmer. I have not seen yaml yet from my studying yet, perhaps it will come later. Sep 29, 2018 at 1:27
  • @theotherswan. Your question was closed, but you can (and should) still accept an answer. Sep 29, 2018 at 2:18
-1

I would reach each line, and every time I come across a line that includes the string "Switch", I count the following line and all subsequent lines until I reach another line that includes "Switch", to which then you reset your item counter and repeat.

Not the answer you're looking for? Browse other questions tagged or ask your own question.