pbPassingBI
/
Python basics for data beginner 6 min

Lists and dictionaries

The two structures you actually need, and how they map to DataFrames.

What you'll be able to do
  • Use lists and dictionaries
  • Index and slice a list
  • See how a dict of lists becomes a DataFrame

Lists

cities = ['Houston', 'Dallas', 'Austin']
cities[0]      # 'Houston'  — zero-based
cities[-1]     # 'Austin'   — counts from the end
cities[0:2]    # ['Houston', 'Dallas']  — end is exclusive
cities.append('El Paso')
len(cities)    # 4
Slicing is end-exclusive

cities[0:2] gives two items, not three. The same rule applies to every slice in Python, including on DataFrames.

Dictionaries

customer = {'name': 'Ana', 'city': 'Houston', 'orders': 12}
customer['name']              # 'Ana'
customer.get('phone', 'n/a')  # 'n/a' instead of an error
customer['phone'] = '555-0100'

Use .get() when a key might be absent — customer['phone'] raises KeyError and stops the notebook.

Why this matters for pandas

A dictionary of lists is the most direct way to build a DataFrame, and it makes the structure obvious:

import pandas as pd

data = {
    'product': ['A', 'B', 'C'],
    'sales':   [100, 150, 90],
}
df = pd.DataFrame(data)

Each key becomes a column; each list holds that column's values. All lists must be the same length.

List comprehensions

squares  = [x * 2 for x in [1, 2, 3]]              # [2, 4, 6]
big      = [x for x in [1, 50, 99] if x > 40]     # [50, 99]

Compact and idiomatic. You will meet them constantly in other people's code, so they are worth reading fluently even if you write loops yourself.

Key points
  • Lists are zero-indexed and slices exclude the end position
  • dict.get(key, default) avoids KeyError on a missing key
  • A dict of lists maps directly onto DataFrame columns
Check yourself