In [4]:
from collections import Counter
In [5]:
Counter('with a string')
Out[5]:
In [6]:
Counter('with a string'.split())
Out[6]:
In [28]:
c = Counter([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 5, 6, 100, 'test'])
In [9]:
c
Out[9]:
In [12]:
c.viewitems()
Out[12]:
In [19]:
for k, v in c.iteritems():
print "key:", k, "value:", v
In [21]:
c.most_common() # descending order of most common
Out[21]:
In [22]:
c.most_common(1)
Out[22]:
In [23]:
c.most_common(3)
Out[23]:
In [34]:
c
Out[34]:
In [30]:
list(c)
Out[30]:
In [31]:
set(c)
Out[31]:
In [32]:
dict(c)
Out[32]:
In [39]:
c.most_common()[:-4-1:-1]
Out[39]:
In [41]:
from collections import defaultdict
In [42]:
d = {'k1':1}
In [43]:
d["k1"]
Out[43]:
In [44]:
d["k2"] # this will get an error because the k2 key doesnt exist
In [45]:
d = defaultdict(object)
In [46]:
d['one'] # this doesn't exist, but in calling for it it will create a new element {'one' : object}
Out[46]:
In [48]:
d['two'] # same, this will add {'two' : object}
Out[48]:
In [50]:
for k, v in d.items():
print "key:", k, "item:", v
In [59]:
e = defaultdict(lambda: 0) # lambda just returns 0 here
In [61]:
e['four']
e['twelve']
Out[61]:
In [64]:
def error():
return 'error'
f = defaultdict(error) #returned item must be callable or None
In [65]:
f['new']
Out[65]:
In [66]:
f.items()
Out[66]:
In [70]:
d_norm = {}
d_norm['a'] = 1
d_norm['b'] = 2
d_norm['c'] = 3
d_norm['d'] = 4
d_norm['e'] = 5
# order isn't preserved since a dict is just a mapping
for k,v in d_norm.items():
print k,v
In [73]:
from collections import OrderedDict
In [77]:
d_ordered = OrderedDict()
d_ordered['a'] = 1
d_ordered['b'] = 2
d_ordered['c'] = 3
d_ordered['d'] = 4
d_ordered['e'] = 5
In [78]:
for k,v in d_ordered.items():
print k, v
In [79]:
from collections import namedtuple
In [81]:
# this is kind of like creating a new class on the fly
# the first parameter of a namedtuple is the name of the class/tuple type
# the second parameter is a space-delimeted list of properties of the tuple
Dog = namedtuple('Dog','age breed name')
sam = Dog(age=2, breed='Lab', name='Sammy')
In [82]:
print sam.age
print sam.breed
print sam.name
In [102]:
Catzz = namedtuple('Cat', 'fur claws name')
mittens = Catzz(fur='fuzzy', claws='sharp', name='Mittens')
print type(mittens)
print type(Catzz)
print mittens[0]
print mittens.claws
print mittens.name
print mittens.count('fuzzy')
print mittens.index('sharp')
In [ ]: