Python for Finance: Analyze Big Financial Data

(Elle) #1
iterkeys

()

Iterator over all keys

itervalues

()

Iterator over all values

keys

()

Copy of all keys

poptiem

(k)

Returns and removes item with key k

update

([e])

Updates items with items from e

values

()

Copy of all values

Sets


The last data structure we will consider is the set object. Although set theory is a


cornerstone of mathematics and also finance theory, there are not too many practical


applications for set objects. The objects are unordered collections of other objects,


containing every element only once:


In  [ 74 ]: s   =   set([‘u’,   ‘d’,    ‘ud’,   ‘du’,   ‘d’,    ‘du’])
s
Out[74]: {‘d’, ‘du’, ‘u’, ‘ud’}
In [ 75 ]: t = set([‘d’, ‘dd’, ‘uu’, ‘u’])

With set objects, you can implement operations as you are used to in mathematical set


theory. For example, you can generate unions, intersections, and differences:


In  [ 76 ]: s.union(t)      #   all of  s   and t
Out[76]: {‘d’, ‘dd’, ‘du’, ‘u’, ‘ud’, ‘uu’}
In [ 77 ]: s.intersection(t) # both in s and t
Out[77]: {‘d’, ‘u’}
In [ 78 ]: s.difference(t) # in s but not t
Out[78]: {‘du’, ‘ud’}
In [ 79 ]: t.difference(s) # in t but not s
Out[79]: {‘dd’, ‘uu’}
In [ 80 ]: s.symmetric_difference(t) # in either one but not both
Out[80]: {‘dd’, ‘du’, ‘ud’, ‘uu’}

One application of set objects is to get rid of duplicates in a list object. For example:


In  [ 81 ]: from random import randint
l = [randint( 0 , 10 ) for i in range( 1000 )]
# 1,000 random integers between 0 and 10
len(l) # number of elements in l
Out[81]: 1000
In [ 82 ]: l[: 20 ]
Out[82]: [8, 3, 4, 9, 1, 7, 5, 5, 6, 7, 4, 4, 7, 1, 8, 5, 0, 7, 1, 9]
In [ 83 ]: s = set(l)
s
Out[83]: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Free download pdf