Python Cheatsheet (v 2.7)

Here’s a few quick references for python developers.

Here are some python tips & tricks that can be useful for beginners.

Merge tuples

t1 = ('a','b','c') 
a1 = ['j','k'] 
result = t1+tuple(a1)
# result == ('a','b','c','j','k')

# note here I'm converting a list into tuple right away - so you can mix/match tuples/lists this way

Dictionary with predefined (prserved) order:

OrderedDict is the structure you’re looking for:

from collections import OrderedDict
ordered = OrderedDict()
regular = {}
#now add elements
#now if you iterate over ordered, you'll get 'test1' then 'test2'

#in this case, iterating over regular.values() will get you 'test2', then 'test1'

Convert list into dictionary

Often after getting data from a database (e.g. MySQL, SQLite, etc.) you get a list:

lst = [(1,'mike'),(2,'jim'),(3,'jane')]

To convert it to a dictionary, simply:

result = dict(lst)
#now result is: {1:'mike',2:'jim',3:'jane'}

If you need to preserve keys order (e.g. if they’re strings) use OrderedDict instead:

from collections import OrderedDict
result = OrderedDict(lst)
#items can be accessed the same as a normal dictionary:
result[2] == 'jim'

Generate colour spectrum

TL;DR: generate a list of hues (here we’ll do 5 of them) and map each hue to RGB: map(lambda c: hsv_to_rgb(c,1,255),linspace(0,1,5))

If you ever needed to get a bunch of (maybe random) colours, e.g. for graphs or a colour wheel, there are plenty of libraries for JS out there, but there’s a VERY easy way to do it with python.
To do this you need to stop thinking in RGB and pick pretty much any other colour model. The most popular ones are HSV and HSL
These colour models are cylindrical and thus you can cycle through them without fancy tricks or nested loops.

# first we need the library to convert colours
# into something we can display (e.g. RGB)
from colorsys import hsv_to_rgb
# next, a shortct to generate float-list:
from numpy import linspace

howMany = 5 #how many colours to generate

# now the fun part
rgbColours = map(lambda c: hsv_to_rgb(c,1,255),linspace(0,1,howMany)) 

#result: [(255, 0.0, 0.0), (127.5, 255, 0.0), (0.0, 255.0, 255), (127.5, 0.0, 255), (255, 0.0, 0.0)]

You can add other things to it if you need, e.g. map(int,hsv_to…) to convert each of the values to int instead of float (if you need it for CSS). Best of all, they’ll be evenly spaced in the colour spectrum.

Convert a list of tuples into a list of values

When retrieving data from some databases you get this kind of result:
But you need them as:
['value1', 'value2', ...]

The easiest way to convert a list of tuples is the zip function.

data = [('val1',),('val2',),('val3',)]
result  = zip(*data)[0]
# now result contains  ('val1','val2','val3')
# if you need to convert this to a list, simply run list(result)

Comments are closed.