3 More Incredible Python Data Structure Tricks

My previous post did really well. I’m guessing you guys really like my Python content so here are 3 more incredible tricks you can use with Python Data Structures.

Extracting a Subset of a Dictionary

Problem

You want to make a dictionary that is a subset of another dictionary.

Solution

This can be easily accomplished using dictionary comprehension.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
prices = {
'DOW J': 28004.89,
'AAPL': 265.76,
'GE': 11.52,
'NKE': 93.04,
'DIS': 144.67
}

# dictionary of stocks worth more than $200
p1 = {key : value for key, value in prices.items() if value > 200}
# {'DOW J': 28004.89, 'AAPL': 265.76}

# dictionary of tech stocks
tech_names = ['AAPL', 'MSFT', 'FB', 'IBM', 'GOOGL']
tech = {key : value for key, value in prices.items() if key in tech_names}
# {'AAPL': 265.76}

Functional Python can be really cool indeed!

Determining the Most Frequently Occurring Item(s) in a Sequence

Problem

You have a sequence of items, and you’d like to determine the most frequently occurring item(s) in the sequence.

Solution

Of course, dictionaries can be used for this problem with the elements of the sequence as keys and the number of times they occur as values. However, this post is about tricks with Data Structures so we have to do something out-of-the-box.

The collections.Counter class is designed for such a problem. It even comes with a handy most_common() method that will give you the answer.

To illustrate, let’s say you have a list of words and you want find out which words occur most often.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
words = [
'Is', 'allowance', 'instantly', 'strangers', 'applauded', 'discourse',
'so', 'Separate', 'entrance', 'companions', 'welcomed', 'sensible', 'laughing', 'why',
'one', 'moderate', 'shy', 'We', 'seeing', 'piqued', 'at', 'garden', 'he',
'As', 'in', 'merry', 'at', 'forth', 'least', 'ye', 'stood.', 'And',
'cold', 'sons', 'yet', 'with', 'Delivered', 'middleton', 'therefore',
'me', 'at', 'Attachment', 'companions', 'man', 'way', 'excellence', 'how',
'her', 'pianoforte', 'allowance', 'at'
]

from collections import Counter
words = words.lower()
word_counter = Counter(words)
top = word_counter.most_common(1)
top_three = word_counter.most_common(3)
print(top) # Output: [('at', 4)]
print(top_three) #Output: [('at', 4), ('allowance', 2), ('companions', 2)]

Under the covers, Counter is just a dictionary that maps the items to the number of occurrences. Also note, Counter objects can be fed any sequence of hashable input items.

Iterating Over all Possible Permutations or Combinations

Problem

You want to iterate over all possible permutations or combinations of a collection of items

Solution

The itertools module provides the required permutations() and combinations() functions for this task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from itertools import permutations

items = ['a', 'b', 'c']
for p in permutations(items):
print(p)
"""
3! or 6 possible permutations
Output:
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
"""

Similarly, we can use the itertools.combinations() function to produce a sequence of combinations of items.

1
2
3
4
5
6
7
8
9
10
from itertools import combinations
for c in combinations(items, 2):
print(c)
"""
(3! / 2!) or 3 possible combinations
Output:
('a', 'b')
('a', 'c')
('b', 'c')
"""

Summary

And that’s it - 3 more simple tricks to make life easier when using Python’s data structures.