Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active October 26, 2016 12:16
Show Gist options
  • Save pokk/fbecd1321aee6cb6827277918a86f70c to your computer and use it in GitHub Desktop.
Save pokk/fbecd1321aee6cb6827277918a86f70c to your computer and use it in GitHub Desktop.
Introduce simple way to use them

Introduction

  1. collections.namedtuple
  2. collections.deque
  3. collections.Counter
  4. collections.OrderedDict
  5. collections.defaultdict

collections.namedtuple

We can use namedtuple to enhance the code readable of a simple kind of class.

collections.deque

The name is double-ended queue. The benfit is that the complexity time of pop() and insert() is speedy.

l.append(5)
l.pop()

list time complexity are O(n) after used them.
deque time complexity are O(1) after used them.

collections.Counter

Just as the name, easy to count the same key in a dict.

collections.OrderedDict

Almost the same as dict, it just adds the order by inputing time.

collections.defaultdict

Almost the same as dict, users can define the default value.

from collections import Counter
s = '''
A Counter is a dict subclass for counting hashable objects.
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
Counts are allowed to be any integer value including zero or negative counts.
The Counter class is similar to bags or multisets in other languages.
'''
c = Counter(s)
# >>> Counter({' ': 51, 'e': 32, 's': 25, 't': 23, 'a': 23, 'o': 22, 'n': 21, 'r': 20, 'i': 19, 'l': 14, 'u': 13, 'c': 12, 'd': 10, 'g': 7, 'h': 6, 'b': 5, '\n': 5, 'y': 4, '.': 4, 'm': 3, 'v': 3, 'C': 3, 'w': 2, 'z': 1, 'f': 1, 'k': 1, 'I': 1, 'j': 1, 'A': 1, 'T': 1})
# Show the top 5 in counter.
c.most_common(5)
# >>> [(' ', 51), ('e', 32), ('s', 25), ('t', 23), ('a', 23)]
from collections import defaultdict
# Set the default value is a string 'N/A'.
dd = defaultdict(lambda: 'N/A')
dd['hello'] = 'python'
print(dd['hello'])
# >>> dd['hello'] = python
print(dd['goodbye'])
# >>> dd['goodbye'] = 'N/A'
# ----------------------------------
members = [
# Sex, Name
['male', 'Jieyi'],
['male', 'Ted'],
['female', 'Peggy'],
['male', 'Mark'],
['female', 'Lucy'],
]
# Set the default value is a list [].
dd = defaultdict(list)
# Because it has a default empty list [], you can just put append without worries.
# This way is more convenient tham dict().
for sex, name in members:
dd[sex].append(name)
# >>> defaultdict(<class 'list'>, {'male': ['Jieyi', 'Ted', 'Mark'], 'female': ['Peggy', 'Lucy']})
# You can do the same way for dict().
d = {}
for sex, name in members:
d.setdefault(sex, []).append(name)
# >>> {'male': ['Jieyi', 'Ted', 'Mark'], 'female': ['Peggy', 'Lucy']}
from collections import deque
d = deque('hello python')
# >>> deque(['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n'])
d.pop()
# >>> deque(['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o'])
d.popleft()
# >>> deque(['e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o'])
d.appendleft('g')
# >>> deque(['g', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o'])
# Right shift the queue.
d.rotate(1)
# >>> deque(['o', 'g', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h'])
from collections import namedtuple
# We can use namedtuple to create a simple object as like kind of class.
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(4, 6)
# >>> Point(x=4, y=6)
p2 = Point(2, 5)
# >>> Point(x=2, y=5)
p3 = p1 + p2
# >>> (4, 6, 2, 5)
# Ofcz p1 and p2 both are tuple so they do the add method, they will be a tuple object.
# ----------------------------------
# We can create how many variables which you like.
Space = namedtuple('Space', ['x', 'y', 'z'])
s1 = Space(3, 5, 2)
# >>> Space(x=3, y=5, z=2)
# ----------------------------------
websites = [
('Google', 'http://www.google.com/', 'Jieyi'),
('Yahoo', 'http://www.yahoo.com/', ' Ted'),
('Ted', 'http://www.ted.com/', 'Snowden')
]
Website = namedtuple('Website', ['name', 'url', 'founder'])
for website in websites:
website = Website._make(website)
# >>> Website(name='Google', url='http://www.google.com/', founder='Jieyi')
# >>> Website(name='Yahoo', url='http://www.yahoo.com/', founder=' ted')
# >>> Website(name='Ted', url='http://www.ted.com/', founder='Snowden')
from collections import OrderedDict
items = [
('A', 1),
('B', 2),
('C', 3)
]
regular_dict = dict(items)
ordered_dict = OrderedDict(items)
# Original dict.
for k, v in regular_dict.items():
print(k, v)
# >>> B 2
# >>> A 1
# >>> C 3
# Ordered dict.
for k, v in ordered_dict.items():
print(k, v)
# >>> A 1
# >>> B 2
# >>> C 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment