3.2.6 - Records and fields (Python)

3.2.6 - Records and fields (Python)

Some related values describe one object but have different meanings and types. You will represent those values as named fields using Python dictionaries, the record equivalent used in this lesson.

Grouping related fields

A record groups related named fields that describe one entity, such as one car or one pupil.

Record

A data structure made of named fields, which may hold different data types.

A car's make, model and registration are strings; price is real and number of doors is integer. An array of prices holds repeated instances of one kind of data, while a car record keeps the different attributes of one car together.

Python has several possible record equivalents. Here a dictionary associates each field name (key) with a value:

Python
car = {
    "make": "Harbour",
    "model": "Compact",
    "registration": "AB12 CDE",
    "price": 7250.50,
    "doors": 5
}
print(car["registration"])

The output is AB12 CDE. Quoted keys such as "price" select named fields rather than numeric positions. Choosing appropriate field types enables arithmetic on prices without treating the registration as a number. Python dictionaries do not enforce a fixed field schema or declared field types; the programmer creates and uses the agreed fields consistently. AQA supplied record definitions do declare named typed fields and use dot notation, such as car.price. Use the syntax of the requested response language.

Using records in a solution

A record field can be read, processed and updated without separating it from the entity it describes.

Python
discounted_price = car["price"] - 500
car["price"] = discounted_price
print(car["model"], car["price"])

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account