Hone

Lessons · Python · list or dict?

Position or name?

A list is for things in order, reached by position; a dict is for things with a name, reached by key.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Choosing wrong makes every later line awkward: searching a list for a user by id, or trying to keep a dict 'in order' of arrival. The right structure makes the code obvious.

How to think about it

How will I get things OUT: by position or by name? Ask how you will get things OUT. 'The third one', 'the next one', 'all of them in order': list. 'The one called X', 'is X here', 'X's value': dict (or set if there is no value).

Worked example

queue = ["ada", "bo"]
Order matters: who is served next. List.
ages = {"ada": 31, "bo": 27}
Lookup by name. Dict.
print(queue[0], ages["bo"])
ada 27. Position on the list, name on the dict.

Your turn

Pick the structure for 'settings looked up by their name'.

settings =  "theme": "dark", "size": 14 

The trap

A list of pairs [("ada", 31), ...] used as a dict. Every lookup becomes a loop. If you look things up by name, make it a real dict.

Practise list or dict? on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.