Memo

Data Types

  • collections.OrderedDict

# Sorting
sortedResults = collections.OrderedDict(sorted(result.items()))

# Sorting by value
sortedResults = collections.OrderedDict(sorted(result.items(), key=lambda x: x[1]))

# Ordering
sortedResults = collections.OrderedDict(sorted(result.items(), key=lambda x: x[1], reverse=True))

{:} instead of %. For example, '%03.2f' can be translated to '{:03.2f}'.

File IO

Read, write, append operation

# Using 'with' to include file close and exception handling.
with open('workfile', 'r') as f # r: read, r+: read / write, w: write, a: append
for line in f:
  print line

Using "encode" or casting to avoid stepping on the pit.

# Through encode
line.encode('ascii', 'ignore')
line.encode('utf8', 'ignore')

# Through casting
def object(line):
  fields = line.split(',')
  id = fields[0]
  amount = fields[1]
  return (int(id), float(amount))

Last updated