Image for post
Image for post

Ops Scripting w. Python: Frequency

Tracking Frequency in Python: Part I

In many operations oriented roles, often times you need to write some scripts for automation. One common type of chore tracking the frequency of something. A typical problem will be to process text from a file, count the occurrence of some event, and then output a small report.

The Problem

Print the shell and number of users that use that shell with a local copy of /etc/passwd file. For this we’ll create a frequency hash, or dict in Python.

The Data

Here’s the local passwd file used for this exercise:


The Output

The output given the report given the data from above would have these counts:

Shell Summary Report:
Shell # of Users
----------------- ------------
/bin/bash 3 users
/bin/false 7 users
/bin/sync 1 users
/usr/sbin/nologin 17 users

The Code

Here’s the boiler plate getting started code used for all the solutions. You can embed your solution in the middle of this. For the frequency hash, we’ll use a dict data structure called counts.

Sample Code with Output Report
for item in list:
for key, value in dictionary.items():
print("{}:{}".format(key, value))


In this article I only wanted to present the problem. In a follow-up articles (two parts), I’ll show ways to solve this with collection loop (for), lambda, and comprehension.

  • formatted output with print(string.format())
  • repetition operator *
  • enumerating and sorting a dictionary
  • 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