Build a label-to-index map from a parallel labels list, then look up rows by string key. With pandas, a DataFrame can carry a named index, and df.loc selects rows by those labels directly — no manual mapping needed.

By hand

With pandas

pd.DataFrame(records, index=labels) assigns string labels as the row index. df.loc[['p', 'r']] selects those rows by label and returns a sub-DataFrame with the matching index.

naive.py
# trace: ignore records
labels = ['p', 'q', 'r', 's']
records = [
    {'name': 'al', 'age': 20},
    {'name': 'bo', 'age': 25},
    {'name': 'cy', 'age': 22},
    {'name': 'di', 'age': 28},
]
label_to_idx = {}
for i in range(len(labels)):
    label_to_idx[labels[i]] = i
keys = ['p', 'r']
names = []
for k in keys:
    idx = label_to_idx[k]
    names.append(records[idx]['name'])
print('RESULT:', names)
library.py
import pandas as pd
from dalib.display import set_display
set_display()

labels = ['p', 'q', 'r', 's']
records = [
    {'name': 'al', 'age': 20},
    {'name': 'bo', 'age': 25},
    {'name': 'cy', 'age': 22},
    {'name': 'di', 'age': 28},
]
df = pd.DataFrame(records, index=labels)
selected = df.loc[['p', 'r']]
print('index:', selected.index.tolist())
print('names:', selected['name'].tolist())
print('shape:', selected.shape)
print('RESULT:', selected['name'].tolist())
index: ['p', 'r']
names: ['al', 'cy']
shape: (2, 2)
RESULT: ['al', 'cy']

Implementation notes

  • loc is label-based: it looks up rows by index value, not by integer position. If the index is ['p', 'q', 'r', 's'], then df.loc['r'] returns the row labelled 'r' regardless of its physical position.
  • Label slices with loc are end-inclusive: df.loc['p':'r'] returns rows p, q, and r. This differs from iloc slices, which are end-exclusive.
  • Passing a list (loc[['p', 'r']]) selects specific labels in the given order; the result index matches the requested order, not the original order.
  • loc also accepts column labels as a second argument: df.loc[['p', 'r'], 'name'] returns just the name column for those rows as a Series.
  • Contrast with iloc (see select-rows-iloc): use iloc for position-based selection, loc for label-based selection.