Python Lists, Tuples, Dictionaries and Sets Explained with Examples
P4.5 List of Dictionaries: How Table Data Looks in Python
Why. A table is many rows. Each row is a dictionary. A list of them is exactly what pandas turns into a DataFrame, and what JSON from an API looks like.
What. A list where every item is a dictionary with the same keys.
| order_id | city | amount |
|---|---|---|
| O1 | Pune | 450 |
| O2 | Mumbai | 1200 |
| O3 | Pune | 300 |
How to read this table: each row is one order. order_id is its ID, city is where it was delivered and amount is the bill in ₹.
How.
Work with table-like data
- Make one dictionary per row.
- Put all rows in a list.
- Loop over rows to read values.
- Add up or filter as needed.
Worked example A — Build the table.
Step 1 — What we do. We write the three orders above as Python data.
Step 2 — Type and run this code.
orders = [
{"order_id": "O1", "city": "Pune", "amount": 450},
{"order_id": "O2", "city": "Mumbai", "amount": 1200},
{"order_id": "O3", "city": "Pune", "amount": 300},
]
print(len(orders))
print(orders[1]["city"])
Step 3 — Output you should see.
3
Mumbai
Step 4 — What it means. There are 3 rows. orders[1]["city"] means row 2, column city = Mumbai.
Worked example B — Total for one city.
Step 1 — What we do. We add up only the Pune orders.
Step 2 — Type and run this code.
orders = [
{"order_id": "O1", "city": "Pune", "amount": 450},
{"order_id": "O2", "city": "Mumbai", "amount": 1200},
{"order_id": "O3", "city": "Pune", "amount": 300},
]
pune_total = sum(o["amount"] for o in orders if o["city"] == "Pune")
print(pune_total)
Step 3 — Output you should see.
750
Step 4 — What it means. Pune total is ₹750. In pandas this becomes one line: df[df.city == "Pune"].amount.sum(). Now you know what happens underneath.
| Container | Brackets | Ordered? | Can change? | Use it for |
|---|---|---|---|---|
| list | [ ] | yes | yes | a column of values |
| tuple | ( ) | yes | no | fixed pairs like (lat, lon) |
| dict | {k: v} | yes (insertion) | yes | one row / lookups |
| set | { } | no | yes | unique values |
How to read this table: each row is one container type and how it behaves.
Ravindra Bagale's Tip
If you can write your data as a list of dictionaries, you can load it into pandas with pd.DataFrame(orders).
Ravindra Bagale's Tip – मराठी
तुमचा data list of dictionaries म्हणून लिहिता आला तर pd.DataFrame(orders) ने तो pandas मध्ये load होतो.
Ravindra Bagale's Tip – हिंदी
अगर आपका data list of dictionaries के रूप में लिखा जा सकता है तो pd.DataFrame(orders) से वो pandas में load हो जाता है.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.