Advanced Python Dictionary and Set Techniques
This article introduces several high‑level Python dictionary and set methods—including fromkeys, merge, setdefault, defaultdict, OrderedDict, as well as set comprehensions and custom hashing—to simplify code, improve readability, and demonstrate practical usage patterns with clear examples.
After covering the basics of dictionaries and sets, this tutorial presents a collection of advanced techniques that are frequently used in real‑world Python development, aiming to make code more concise and readable.
1. Dictionaries
1.1 fromkeys
The fromkeys method creates a new dictionary with specified keys and a default value (None if not provided). Example:
<code>In [1]: dict.fromkeys(['a', 'b', 'c'])
Out[1]: {'a': None, 'b': None, 'c': None}
In [2]: dict.fromkeys(['a', 'b', 'c'], 0)
Out[2]: {'a': 0, 'b': 0, 'c': 0}</code>1.2 merge
Dictionary merging differs between Python 2 and Python 3. In Python 2, update modifies the original dictionary, while copying and updating a shallow copy preserves the original. Python 3 offers the | operator for merging without side effects.
<code># Python 2 example
x = {'a': 1, 'b': 2}
y = {'b': 10, 'c': 11}
x.update(y)
print(x) # {'a': 1, 'b': 10, 'c': 11}
# Python 3 example
z = dict(x.items() | y.items())
print(z) # {'c': 11, 'a': 1, 'b': 10}</code>1.3 setdefault
The setdefault method returns the value for a key if it exists; otherwise it inserts the key with a default value. Example:
<code>d = {}
d.setdefault('a', 1) # returns 1
print(d) # {'a': 1}</code>A more Pythonic way to count characters uses setdefault inside a loop:
<code>s = 'sdsdes'
d = {}
for c in s:
d[c] = d.setdefault(c, 0) + 1
print(d) # {'s': 3, 'd': 2, 'e': 1}</code>1.4 defaultdict
The defaultdict class from the collections module automatically creates missing keys with a default factory (e.g., int for zero). Example:
<code>import collections
s = 'sdsdes'
d = collections.defaultdict(int)
for c in s:
d[c] += 1
print(d) # defaultdict(int, {'s': 3, 'd': 2, 'e': 1})</code>Using a lambda as the factory allows custom default values:
<code>d = collections.defaultdict(lambda: 0)
print(d['b']) # 0</code>1.5 OrderedDict
Before Python 3.6, dictionaries did not preserve insertion order, so OrderedDict from collections was used to maintain order. After Python 3.6, the built‑in dict retains order, but OrderedDict still provides order‑sensitive equality checks.
<code># Using OrderedDict
import collections
od = collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(list(od.items())) # [('a', 1), ('b', 2), ('c', 3)]
</code>2. Sets
2.1 Set comprehensions
Sets also support comprehension syntax using curly braces. They automatically deduplicate elements and may reorder them.
<code>{s for s in [1, 2, 1, 0]} # {0, 1, 2}
{s for s in [1, 2, 3] if s % 2} # {1, 3}
{(m, n) for n in range(2) for m in range(3,5)} # {(3, 0), (3, 1), (4, 0), (4, 1)}</code>2.2 Hashing and custom objects as keys
Only hashable objects can be dictionary keys. Lists are unhashable, raising TypeError . Custom classes become hashable by defining __hash__ (and optionally __eq__ ) methods.
<code>class A:
def __init__(self, a, b):
self.key = (a, b)
def __eq__(self, other):
return self.key == other.key
def __hash__(self):
return hash(self.key)
d = {}
d[A(1,2)] = 4
print(d) # {<A object at ...>: 4}
print(d[A(1,2)]) # 4</code>With proper __hash__ and __eq__ , instances can also be added to a set, automatically handling deduplication.
<code>s = set()
s.add(A(1,2))
s.add(A(1,2))
print(s) # {<A object at ...>}</code>These techniques illustrate how Python’s built‑in data structures can be leveraged for more efficient and expressive code.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.