> For the complete documentation index, see [llms.txt](https://ysfang82.gitbook.io/development-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ysfang82.gitbook.io/development-notes/programming-langauges/python/memo.md).

# Memo

## Data Types

* collections.OrderedDict

```python
# 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))
```

## [String Formatting](https://docs.python.org/3/library/string.html#format-specification-mini-language)

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

## File IO

Read, write, append operation

```python
# 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.

```python
# 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))
```
