3 Incredible Python Data Structure Tricks

Python provides a variety of useful built-in data structures, such as lists, sets, and dictionaries. For the most part, the use of these data structures is quite straightforward. However, common questions concerning iteration, unpacking, searching, and sorting often arise. So I decided to make a list of 3 incredible tricks that will make your life a lot easier when working with common Python data structures.

“””
P.S: Apologies for not posting more regularly - I have been very busy recently - spending a lot of time learning about investment banking and FinTech for my Spring Week applications. Hopefully, this post will be a start to a string of fortnightly posts.
“””

Unpacking a Sequence into Separate Variables

Problem

You have an N-element tuple or sequence that you would like to unpack into a collection of N variables.

Solution

Use a simple assignment operation.

1
2
3
data = ['ACME', 50, 91.1, (2012, 12, 21)]
name, shares, price, date = data
print(name) #ACME

Unpacking Elements from Iterables of Arbitrary Length

Problem

You need to unpack N elements from an iterable, but an iterable may be longer than N elements, causing a “too many elements to unpack exception”

Solution

Use a star expression

1
2
3
record = ('Guido Van Rossum', 'guido@python.org', '777-555-1212', '847-555-1212')
name, email, *phone_numbers = record
print(phone_numbers) #['777-555-1212', '847-555-1212']

Find Commonalities in Dictionaries

Problem

You have two dictionaries and you want to find out what they have in common (keys, values, etc.)

Solution

Consider two dictionaries:

1
2
3
4
5
a = {
'x': 1,
'y': 2,
'z': 3
}
1
2
3
4
5
b = {
'w': 10,
'x': 11,
'y': 2
}

And now simply use common set operations using the keys() and items() methods.

1
2
3
4
5
6
7
8
# Find keys in common
a.keys() & b.keys() # {'x', 'y'}

# Find keys in a that are not in b
a.keys() - b.keys() # {'z'}

# Find (key, value) pairs in common
a.items() & b.items() # {('y', '2')}

Summary

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