Troubleshooters.Com and Python Patrol present:

Python 3 Quick Tips

See the Troubleshooters.Com Bookstore.



The purpose of this web page is to provide quick tips about various aspects of Python 3. It isn't thorough or detailed: Instead just enough to get you going to some degree.

JSON Quick Tips

JSON is a nice, easy and relatively secure way of writing Python data to stdout or a file.

To write a Python list or dict or multilevel structure (but not executable code) to stdout, use json.dumps:

import json
import sys

info['name'] = {'fname': 'Steve', 'lname': 'Litt'}
info['job'] = 'Troubleshooter'
print(json.dumps(info, fout, sort_keys=True, indent=3))

The preceding writes dict info to stdout in JSON format. In the preceding code, the sort_keys and indent arguments make the json more readable. They're not strictly necessary, but make debugging a heck of a lot easier. If the structures you're writing are so huge as to slow things down or consume too much RAM or disk, you can remove these two arguments and just use the defaults.


Please be aware that json.dumps() does not "dump" the JSON content to stdout, it only "dumps" it to a string. The print() around json.dumps() is necessary to output to stdout.

If, for some reason, you don't want to perform the print(), you can use json.dump() instead, as follows:
json.dump(info, sys.stdout, sort_keys=True, indent=3)

Writing a Python 3 data structure to a specific file is only a little more work, as follows:

import json
import sys

info['name'] = {'fname': 'Steve', 'lname': 'Litt'}
info['job'] = 'Troubleshooter'
fout = open('junk.jnk', 'w')
json.dump(info, fout, sort_keys=True, indent=3)

The preceding code writes data structure info to a file called junk.jnk. Obviously, if you meant the file to be permanent, you'd name it something else. The preceding code differs from the code before it only in these ways:

Importing a JSON file into a Python 3 data structure uses either the json.loads() function or the json.load()

To have Python 3 open a JSON file on disk and use it to create a data structure, you can use something like the following code:

import json
import sys

fin = open('junk.jnk', 'r')
info2 = json.load(fin)

If the JSON data is coming in via stdin, the preceding simplifies to the following:

import json
import sys

info2 = json.load(sys.stdin)

This concludes the quick tips for JSON in Python 3.

Accessing Individual Dict Elements Quick Tips

When accessing a Python dictionary, a succession of questions must be answered:

  1. Is the key in the dict?
  2. If it's in the dict, is its value None?
  3. If it's in the dict and not None, what is the value for the key?

The preceding could be answered with exceptions, but I'm not a fan of using error handling to perform normal expected processing. So instead, I do it with regular Python 3.

Is the key in the dict?

This can be ascertained using the following:

if 'mykey' in mydict:

The preceding can be done with negative logic, as follows:

if not 'mykey' in mydict:

Testing for None Value

It's vital to understand that you can't test for a None value for a key until it's for sure that key exists in the dictionary. That determination was discussed in the preceding subsection. Once you know the key exists, testing for a None value is as simple as the following:

if mydict['mykey'] in mydict:

Further Refinements

If necessary, once you know the key exists and the value isn't None, if need be, you can test the value's type, don't test for equality, but instead use the is verb as follows:

if type(mydict['mykey']) is str:
elif type(mydict['mykey']) is int:
elif type(mydict['mykey']) is dict:
elif type(mydict['mykey']) is list:

This concludes the quick tips for accessing dict elements in Python 3.

Iterating Dicts Quick Tips

There are zillions of ways to iterate a Python dict, some more efficient than others, some more Pythonic than others. The following is one of my favoriates for iterating a dict without sorting:

for mykey,myval in mydict.items():
    process_this_item(mydict, mykey, myval)

This concludes the quick tips for iterating dict elements in Python 3.

Accessing Individual List Items Quick Tips

First of all, I'm a big fan of .append() and .insert() rather than adding elements by number.

When accessing a Python list, a succession of questions must be answered:

  1. Is the subscript in the list?
  2. If it's in the list, is its value None?
  3. If it's in the list and not None, what is the value for the subscript?

Is tthe subscript in the list?

My favorite way of doing this is as follows:

length = len(mylist)
if my_desired_subscript < length:
   work_with_value(mylist, mysubscript)


For the sake of speed with big lists, the preceding code only calls once. This fails if items are added or deleted from the list between the test and the action, or if they're added or deleted in a loop. As in most languages, you should use a while loop instead of a for loop if elements are deleted or added.

The following is a while loop that iterates over a list of dicts, adding a new key/value pair to each element that is non-None, and deleting any elements that have value None. Of course, it stops before exceeding the array bounds:

while i < len(mylist):
        if not mylist[i]:
            i -= 1
            mylist[i]['additional'] = i
        i += 1

This concludes the quick tips for accessing list elements in Python 3.