Python Reference Code Snippets


Similar to the command cheat sheets I publish, this post will serve as a quick reference for short and simple Python code snippets I have used in prior projects.

Pretty Print JSON Output with Python

Un-formatted JSON can be very difficult to read. For example, take the following JSON:

{"key-one": "value-one", "key-two": "value-two"}

This example is simple to read because it is simple JSON, but it can quickly become un-readable with more keys, values, lists, and nesting of all those things.

To quickly transform the JSON output into a more human-readable format, pipe the JSON through the python -m json.tool command to transform what you see above into the following “pretty” JSON output:

{
    "key-one": "value-one",
    "key-two": "value-two"
}

If you want to quickly print the value of a JSON key, you can do so using the Python command with the Python code to parse the JSON passed as a string.

For example, take the following JSON:

{
    "key-one": "value-one",
    "key-two": "value-two"
}

To print the value of key-one, pipe the JSON to the following Python command:

python -c 'import json,sys;obj=json.load(sys.stdin); print obj["key-one"]'

Sort IP Addresses from a File

Save and point the following Python script at a file - python script.py input.txt - which contains a list of IP addresses with one IP address per line.

#!/usr/bin/env python

from netaddr import *
import sys

input = str(sys.argv[1])

with open(input, 'r') as file:
    ips = []
    for ip in file:
        ips += [IPAddress(ip)]

ips = sorted(ips)

for ip in ips:
    print ip

Lambda Sort Strings from a File

The Python code below was used in a unique situation where I needed to sort a text file containing hostnames with the following format:

501325-object01.example.com
501319-infra02.example.com
501324-cinder01.example.com
501320-infra03.example.com
501321-logging01.example.com
501327-object03.example.com
501323-compute02.example.com
501322-compute01.example.com
501326-object02.example.com
501300-infra01.example.com

Save and point the following Python script at a file - python script.py input.txt - that contains a list of hostnames with one hostname per line.

import sys

input = str(sys.argv[1])

with open(input, 'r') as file:
    foo = file.readlines()

foo.sort(key = lambda x: x.split(".")[0].split("-",1)[1:])

for line in foo:
    print line.strip()

If you found this post useful, you can help support this site and get something for yourself by signing up for any of the services listed below through the provided links.

The following links are part of affiliate programs, and I will receive a referral payment from any of the services you sign-up for.

  • Get Faster Shipping: Perhaps you're about to order some stuff on Amazon but want to get more value out of the money you would normally pay for shipping. Sign-up for a free, 30-day trial of Amazon Prime to get free two-day shipping, access to thousands of movies and TV shows, and more.
  • Start Investing Now: Are you looking to start investing some of your disposable saved income? Get started by opening an account with Webull, where upon sign-up and opening a brokerage account with an initial deposit of at least $100 you will receive 1 stock valued (subject to change based on normal market movement) between $8 and $1600.

Thanks for reading and take care.