
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.
In this series, I will present the small coding challenge, and then provide some solutions using Python.
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
.
Python 3 has its own method to format strings using format()
method, and similar other languages Python has a repetition operator *
.
In Python, you can iterate through not only lists, but also dictionaries:
for item in list:
print(item)for key, value in dictionary.items():
print("{}:{}".format(key, value))
You can also sort a dictionaries by its keys with sorted(dictionary.items())
.
Conclusion
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.
Some takeaways:
- creating an empty dictionary, e.g.
newdict = {}
- formatted output with
print(string.format())
- repetition operator
*
- enumerating and sorting a dictionary
- the
in
operator