78 East LabsApply
Academy · Python for Data · The language, briefly

Lists and dictionaries

The two containers everything else is built from, and the one question that tells you which you need.

Video being recorded
About 10 minutes. The written lesson below is complete — read it now, the video is an alternative rather than a replacement.

Almost every structure in data work is a list, a dictionary, or a nesting of the two. A CSV row is a dictionary. A CSV file is a list of them. A JSON response from an API is both, several layers deep.

A list is ordered

cities = ["Chennai", "Kochi", "Pune"]

cities[0]        # "Chennai" — counting starts at zero
cities[-1]       # "Pune" — negative counts from the end
len(cities)      # 3
cities.append("Surat")

Use a list when position matters or when you simply have several of the same kind of thing.

A dictionary is labelled

student = {"name": "Asha", "city": "Kochi", "marks": 88}

student["name"]              # "Asha"
student["marks"] = 91        # change it
student.get("email")         # None, rather than an error

Use a dictionary when you want to look something up by name rather than by position.

That .get() is worth remembering now. student["email"] on a missing key raises an error and stops your program; .get() hands back None. Real data is full of missing keys, and which of those two behaviours you want is a decision you should make on purpose.

The question that decides it

Do I want to ask "what is the third one?" or "what is the city one?"

Position → list. Name → dictionary.

Nesting them is normal

students = [
    {"name": "Asha", "city": "Kochi", "marks": 88},
    {"name": "Ravi", "city": "Pune", "marks": 74},
]

students[1]["city"]   # "Pune"

That shape — a list of dictionaries — is what a table looks like in plain Python, and it is exactly what you get back when you read a CSV before you hand it to anything cleverer.

Read students[1]["city"] left to right: take the list, take item 1, take its city. Long chains of brackets are not mysterious; they are just several of those steps in a row.

Try this

Build a list of three dictionaries describing three things you own. Print the name of the second one. Then add a fourth to the list and print how many you have.

It takes two minutes and it is the whole of this lesson.