Simple Python example programs with explanations
Been doing a lot of Python programming recently and have found that I keep writing the same kinds of utilities. I thought I’d define them all here in functions so that I could cut and paste them as and when I need them. If you’re lucky I’ll write a little explanation (or tutorial) of how they work for the novice Pythoners out there.
Display sorted environment
import os
def printenv():
s = sorted(os.environ.items())
for e in s:
print "%s=%s" % e
os.environ
is a map (collection of key/value pairs) so items turns it into a list of tuples so that it can be iterated over in a for loop. Each tuple contains the key and value of the map entry. The body of the for loop could also be written:
map_key = s[0]
map_value = s[1]
print "%s=%s" % (map_key, map_value)
or
map_key, map_value = s
print "%s=%s" % (map_key, map_value)
but you would only be adding extra stages.No feedback yet
Form is loading...