Image for post
Image for post

Ops Scripting w. Python: Frequency 2

Tracking Frequency in Python: Part II

Updated: 2020–05–24 for clarity

The Solutions

These solutions will use a collection loop for. I call them collection loop as the loop construct iterates over a collection, which in our case a collection of lines from the passwd file.

Solution 1: Basic Collection loop

We open the file and iterate line by line in this example. To keep things simple, we will not handle errors:

line = line.rstrip()         # strip newline
line_items = line.split(':') # split up line by ':' divider
shell = line_items[6] # slice off 7th item
shell = line.rstrip().split(':')[6]
if shell:
# do stuff with that shell as a key
# initialize new key if key doesn't exist in dict
if shell not in counts:
counts[shell] = 0
# increment the count
counts[shell] += 1

Solution 2: Dict get Method

Instead conditionally setting the frequency count, we can use the get method that comes with the dict class. This will return a default value if the key is not found, which should be 0, or it will return the value. Either way, we increment the value by one to increase the count.

Solution 3: DefaultDict

Another method is to just auto-initialize all keys that are referenced for the first time to 0 with dict subclass called defaultdict from the collections library.


From these solutions, the you should have picked up the following takeaways for Python:

  • Splitting a String
  • List Slicing (or indexing in this case)
  • Testing variable is initialized
  • 3 ways to initialize default value in dict class
  • the in operator

Written by

Linux NinjaPants Automation Engineering Mutant — exploring DevOps, Kubernetes, CNI, IAC

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store