Troubleshooters.Com and Python Patrol present:
Python 3 Quick Tips
Copyright (C) 2021 by Steve Litt -- Legal
See the Troubleshooters.Com Bookstore.
CONTENTS:
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 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:
#!/usr/bin/python3 import json import sys info={} 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.
NOTE:
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:
#!/usr/bin/python3 import json import sys info={} info['name'] = {'fname': 'Steve', 'lname': 'Litt'} info['job'] = 'Troubleshooter' fout = open('junk.jnk', 'w') json.dump(info, fout, sort_keys=True, indent=3) fout.close()
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:
#!/usr/bin/python3 import json import sys fin = open('junk.jnk', 'r') info2 = json.load(fin) fin.close()
If the JSON data is coming in via stdin, the preceding simplifies to the following:
#!/usr/bin/python3 import json import sys info2 = json.load(sys.stdin)
This concludes the quick tips for JSON in Python 3.
When accessing a Python dictionary, a succession of questions must be answered:
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.
This can be ascertained using the following:
if 'mykey' in mydict: perform_operations_on_this_key()
The preceding can be done with negative logic, as follows:
if not 'mykey' in mydict: perform_operations_for_missing_key()
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: perform_normal_operations() else: assign_value_to_key() perform_operations_for_missing_key()
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: perform_string_operations() elif type(mydict['mykey']) is int: perform_int_operations() elif type(mydict['mykey']) is dict: perform_dict_operations() elif type(mydict['mykey']) is list: perform_list_operations() else: perform_oddball_type_operations() assign_value_to_key() perform_operations_for_missing_key()
This concludes the quick tips for accessing dict elements in Python 3.
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.
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:
My favorite way of doing this is as follows:
length = len(mylist) if my_desired_subscript < length: work_with_value(mylist, mysubscript)
WARNING!
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]: del(mylist[i]) i -= 1 else: mylist[i]['additional'] = i i += 1
This concludes the quick tips for accessing list elements in Python 3.
=================================================================
=================================================================
=================================================================
=================================================================