2/29
Part 1 of 6 · The formatLearn and do

Store a record as a dict inside a dict

On the test, the statement stays on screen while you code. Level 1 has three methods, and you write them one at a time, starting with set:

  • set(key, field, value) stores value under field in the record key. It creates the record if there isn't one, and replaces the value if the field already has one.

Before any code, decide how to store the data. A record is a key that holds fields, and each field holds a value. So the database is a dict from key to a dict from field to value. Here it is by hand:

records = {}
records["user1"] = {"name": "Ada"}
records["user1"]["city"] = "London"
print(records)
{'user1': {'name': 'Ada', 'city': 'London'}}

The second line made the record. The third added a field to a record that was already there. set has to do both, depending on whether the key is new. setdefault does exactly that: it returns the dict stored under a key, and stores an empty one there first if the key is missing.

inner = records.setdefault("user2", {})
inner["name"] = "Alan"
print(records["user2"], records.setdefault("user1", {}))
{'name': 'Alan'} {'name': 'Ada', 'city': 'London'}

For the new key it made an empty record. For user1 it handed back the record that was already there, untouched.

In the editor, write set. It prints the records after three calls.