Thursday, 13 October 2011

Python dicts and lists

Using zip

Converting to list of tuples to dict
l = [1,'a',2,'b']
tups = zip(l[::2],l[1::2])
  [(1, 'a'), (2, 'b')]

d = dict(tups)
  {1: 'a', 2: 'b'}
d.items()
  [(1, 'a'), (2, 'b')]

zip(*tups)
  [(1, 2), ('a', 'b')]
[d.keys(),d.values()]
  [[1, 2], ['a', 'b']]

Enumerating lists and dictionaries

for index,value in enumerate(list): pass
for key,value in dictionary.iteritems(): pass

## Declaring a dictionary

In [168]:dict(a=1,b=3,c=4)
Out[168]:{'a': 1, 'b': 3, 'c': 4}

#When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print i, v
#To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
>>> for q, a in zip(questions, answers):
...     print 'What is your %s?  It is %s.' % (q, a)

#REVERSE ZIP: Allows to avoid using two keys, values calls when getting a dictionary in two lists
In [95]:d.items()
Out[95]:[(1, 2), (3, 4), (5, 6)]
In [96]:li,la = zip(*d.items())
In [97]:li
Out[97]:(1, 3, 5)
In [98]:la
Out[98]:(2, 4, 6)

...     
#To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
>>> for i in reversed(xrange(1,10,2)):
...     print i
...
#To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print f

## Super Slicing!!!

In [130]:range(1000)[60:100:5]
Out[130]:[60, 65, 70, 75, 80, 85, 90, 95]

In [132]:[0,1,2,3,4,5,6,7][::2]
Out[132]:[0, 2, 4, 6]
        

Join many lists together

import operator
l = [[1,2,3],[4,5,6],[7,8,9]]
print reduce(operator.add,l)
   [1,2,3,4,5,6,7,8,9]
To avoid exceptions if argument list is empty ...
l = [[1,2,3],[4,5,6],[7,8,9]]
reduce(list.__add__,l,[])
 [1,2,3,4,5,6,7,8,9]
l = []
reduce(list.__add__,l,[])
 []

Using itemgetter

operator.itemgetter allows to create a generic method to retrieve several elements of a sequence or mapping.
from operator import itemgetter

first = itemgetter(0)
first([1,2,3])
 1

itemgetter('a','c')({'a':1,'b':2,'c':3})
 (1,3)

No comments:

Post a Comment