Skip to content
Bronze 7 min read · Basics 3 practice problems ↓

Dict, set and list methods

Most data code is a few loops over dicts, sets and lists. Knowing their methods well means shorter code and fewer surprises: a default that gets built on every call, two keys that secretly share one list, a remove that only removes the first match. This lesson walks through the methods you will use every day, with the traps in each.

Foundations · Python for data engineers · Bronze · Python basics for data engineers, lesson 1 of 3

In plain words first

dict: a menu card

Look up a dish and read its price. Ask for a dish that is not on the menu and you can choose what to get back instead of an error.

set: a stamp collection

Each stamp is there once or not at all. Comparing two collections ("which do we both have?") is one line.

list: a delivery route

Stops in order. You can add at the end, insert in the middle, and read any stretch of the route.

You already know what lists, dicts and sets are for. This lesson is the toolbox on each of them: the methodsmethod: A function defined inside a class and called on an object, like name.upper() or order.total(). Learn more → data engineers call every day, and the few that behave differently from what their name suggests.

Dict methods

MethodWhat it does
d.get(k, default)The value, or default (None if you give none) when the key is missing. Never raises.
d.update(other)Copies every pair from other into d, overwriting keys that exist.
d.keys(), values(), items()Views: live windows onto the dict, not copies.
d.pop(k, default)Removes the key and returns its value; with a default, a missing key returns it instead of raising KeyError.
d.popitem()Removes and returns the pair added last.
Python · reading, merging, viewing and removing
prices = {"dosa": 60, "chai": 20}

print(prices.get("vada"), prices.get("vada", 0))  # missing: None, or your default
prices.update({"chai": 25, "vada": 40})  # change one value, add one key
print(prices)

items = prices.items()  # a live view of the dict, not a copy
prices["idli"] = 30
print(len(items), list(prices.keys()))

print(prices.pop("dosa"), prices.pop("pizza", "no such dish"))
print(prices.popitem())  # removes the pair added last
print(prices)

Output from a real run

None 0
{'dosa': 60, 'chai': 25, 'vada': 40}
4 ['dosa', 'chai', 'vada', 'idli']
60 no such dish
('idli', 30)
{'chai': 25, 'vada': 40}

The view printed 4 although it was created when the dict had 3 keys: views follow the dict as it changes. Since Python 3.7 a dict also keeps the order keys were first added, which is why popitem() knows which pair is "last". Sets make no such promise.

setdefault, defaultdict and fromkeys

d.setdefault(k, value) returns d[k], first inserting value if the key is missing. It is handy for one-off grouping. The catch is that value is an ordinary argument, so Python builds it on every call, even when the key already exists. defaultdict only calls its factory for a new key.

dict.fromkeys(keys, value) gives every key the same value object. With a number that is fine; with a list, all keys share one list.

Python · when the default is built, and one list behind two keys
from collections import defaultdict


def new_list():
    print("  a new list was built")
    return []


orders = [("pune", "o1"), ("pune", "o2")]

by_city = {}
for city, order_id in orders:
    by_city.setdefault(city, new_list()).append(order_id)  # built on every call
print(by_city)

grouped = defaultdict(new_list)
for city, order_id in orders:
    grouped[city].append(order_id)  # built only for a new key
print(dict(grouped))

shared = dict.fromkeys(["pune", "goa"], [])  # ONE list behind both keys
shared["pune"].append("o1")
print(shared)
print(dict.fromkeys(["pune", "goa"], 0))  # fine: a number cannot change in place

Output from a real run

  a new list was built
  a new list was built
{'pune': ['o1', 'o2']}
  a new list was built
{'pune': ['o1', 'o2']}
{'pune': ['o1'], 'goa': ['o1']}
{'pune': 0, 'goa': 0}

Set methods

add puts one item in. To take one out, discard does nothing when the item is missing, while remove raises KeyError; choose based on whether a missing item is a bug. The operators compare whole sets at once: | union (in either), & intersection (in both), - difference (in the first only).

Python · restaurants open today and yesterday
open_now = {"spice-hub", "tiffin-co"}
open_now.add("dosa-den")
open_now.discard("pizza-place")  # not there: nothing happens
try:
    open_now.remove("pizza-place")
except KeyError as e:
    print("remove raised KeyError:", e)

yesterday = {"spice-hub", "chai-point"}
print(sorted(open_now | yesterday))  # union: open on either day
print(sorted(open_now & yesterday))  # intersection: open on both days
print(sorted(open_now - yesterday))  # difference: open today only

emails = ["Asha@x.com", "asha@x.com ", "ben@x.com"]
print(sorted({e.strip().lower() for e in emails}))  # clean first, then dedupe

Output from a real run

remove raised KeyError: 'pizza-place'
['chai-point', 'dosa-den', 'spice-hub', 'tiffin-co']
['spice-hub']
['dosa-den', 'tiffin-co']
['asha@x.com', 'ben@x.com']

The last line is the usual way to deduplicate: a set comprehensioncomprehension: A one-line way to build a list, set or dict from another iterable, like [x * 2 for x in xs if x > 0]. Learn more → that cleans each value first, so "Asha@x.com" and "asha@x.com " count as one. Sets have no order, so sort when you print or return them.

List methods and slicing

MethodWhat it does
append(x) / extend(xs)Adds one item / adds every item of an iterableiterable: Anything you can loop over with for: a list, a string, a dict, a range, a file. Calling iter() on it gives a fresh iterator. Learn more →.
insert(i, x)Puts x before position i. O(n): everything after it shifts.
remove(x)Removes the first item equal to x; raises ValueError if there is none.
index(x) / count(x)Position of the first match (ValueError if none) / how many matches.
xs[a:b], xs[::-1]A new list from position a up to, not including, b / a reversed copy.
Python · building and reading a route
stops = ["hub", "dosa-den"]
stops.append(["chai", "vada"])  # adds ONE item: the list itself
print(stops)

stops = ["hub", "dosa-den"]
stops.extend(["chai", "vada"])  # adds each item
stops.insert(1, "tiffin-co")  # goes before position 1
stops.append("chai")
stops.remove("chai")  # removes the FIRST match only
print(stops)
print("vada is at", stops.index("vada"), "| chai appears", stops.count("chai"), "time")
try:
    stops.remove("pizza")
except ValueError:
    print("remove of a missing item raises ValueError")

print(stops[1:3], stops[-2:], stops[::-1])
copy = stops[:]  # a new list with the same items (a shallow copy)
copy.append("end")
print(len(stops), len(copy))

Output from a real run

['hub', 'dosa-den', ['chai', 'vada']]
['hub', 'tiffin-co', 'dosa-den', 'vada', 'chai']
vada is at 3 | chai appears 1 time
remove of a missing item raises ValueError
['tiffin-co', 'dosa-den'] ['vada', 'chai'] ['chai', 'vada', 'dosa-den', 'tiffin-co', 'hub']
5 6

A slice always builds a new list, so stops[:] is a quick copy: appending to copy left stops at 5 items. It is a shallow copyshallow copy: A new outer container holding the same inner objects. Changing an inner list changes it in the original too. Learn more →, though: lists inside it are shared (the mutability lesson shows why).

Common mistakes

  • Building an expensive default with setdefault — The default is built on every call, even when the key exists. Use defaultdict, or check with in first.
  • dict.fromkeys(keys, []) — Every key shares one list, so appending to one appends to all. Use {k: [] for k in keys}.
  • append when you meant extend — append(["a", "b"]) adds one nested list. extend adds each item.
  • Using remove to delete every match — It removes only the first one, and raises ValueError when there is none. Build a new list with a comprehension instead.

Key takeaways

  • get and pop take a default, so a missing key needs no try/except.
  • Views from keys(), values() and items() follow the dict as it changes.
  • Dicts keep insertion order; sets have none, so sort them for output.
  • Set operators | & - answer "either", "both" and "only here" in one step.
  • A slice builds a new list; [::-1] is a reversed copy.

Interview prep

THE QUESTION

"What is the difference between dict.get, setdefault and a defaultdict?"

get only reads: it returns the value or a default and never changes the dict. setdefault reads and, when the key is missing, inserts the default and returns it, so it can start a group in one line; but its default argument is built on every call. A defaultdict calls its factory only when a missing key is used, which makes it the cleaner choice for grouping or counting in a loop. I convert a defaultdict back to a plain dict before returning it, so readers of the result cannot create keys by accident.

Avoid: "setdefault and defaultdict are the same thing". They give the same result for grouping, but setdefault builds its default on every call and changes the dict only when needed, while defaultdict also creates keys when you merely read them.

Follow-ups · answer out loud, then open

Follow-up"How would you find the ids that are in yesterday's export but missing from today's?"
Turn both lists into sets and take the difference: set(yesterday) - set(today). It is O(n + m) instead of a nested loop, it ignores duplicates, and I would sort the result before returning it because sets have no order.
Scenario"A config loader builds dict.fromkeys(sections, {}) and later every section shows the same settings. Why?"
fromkeys puts the same dict object behind every key, so writing to one section writes to all of them. I would build a fresh dict per key with a comprehension: {s: {} for s in sections}.
Trap"list.remove(x) deletes every x in the list."
It removes only the first match and raises ValueError when there is none. To drop every match I build a new list: [v for v in xs if v != x].

Check yourself

4 questions

prices.get("vada") when "vada" is missing returns...

Show the answer

None. get returns None unless you pass another default.

d = dict.fromkeys(["a", "b"], []); d["a"].append(1). What is d["b"]?

Show the answer

[1]. Both keys share the same list object.

{"a", "b"} - {"b", "c"} is...

Show the answer

{"a"}. Difference keeps what is in the first set only.

xs = [1, 2]; xs.append([3, 4]); len(xs) is...

Show the answer

3. append adds the list as one item.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Python basics for data engineers · lesson 2 of 3 · 6 min read
Strings and built-in functions
split, join, strip, f-strings, zip, enumerate, any, all, min, max and sorted, and their surprises.

Related lessons

Primary sources: Built-in types: dict, set and list