Typefully

Understanding... Mapping

Avatar

Share

 • 

3 years ago

 • 

View on X

––– Day 3 ––– ––– Mapping ––– Today, we focus in mappings In a sequence, as we saw yesterday, the order of the items matters In a mapping, what matters is the relationship between keywords and the objects stored in the data structure
Rather than referring to items based on their position in the sequence, you refer to them based on a label you assign to each item
The most common mapping in Python is the dictionary in which each item is a key-value pair You use the key to refer to the value stored There are some other mappings in the `collections` module, too.
Here’s an example of a dictionary which shows how each keyword is mapped to a value: >>> points = {"Stephen": 10, "Sarah": 12} >>> points["Sarah"] 12
All mappings are iterable, which means you can use them in a `for` loop and other places where iteration is needed Here's a reminder of the first day in this series which talked about iterables: twitter.com/s_gruppetta_ct/status/1625544155786285057
When you iterate through a dictionary, for example, your program will go through the keys of the dictionary: >>> for item in points: ... print(item) ... Stephen Sarah
You can also use square brackets to get items from a mapping, as you’ve seen with `points["Sarah"]` above However, mappings are not limited to integer indices in the square brackets as was the case with sequences
Note that, as of Python 3.6, dictionaries are also ordered. However, this is not a defining feature of this type of data structure For example, two dictionaries with the same key-value pairs but in different orders will still evaluate as equal when using `==`
And even though a dictionary is ordered, it still cannot be regarded a sequence since the keys are not limited to integer indices `points[0]` will raise an error (unless `0` is one of the dictionary keys!) since there’s no such thing as the “first” item in a dictionary
––– Etymology Corner ––– The origins of the word don’t really help us understand mappings as they did with iterables and sequences. The meaning of "mapping" in programming comes from the modern meaning of the word
A map shows us where countries are in the world, say, mapping their names to a geographical location A Python mapping does something similar with the keywords and the objects they “map” onto
But, if you’re interested, the Latin 'mappa' means "a cloth" (on which the original maps were drawn on)
––– Tomorrow: Container –––
Avatar

Stephen Gruppetta

@s_gruppetta_ct

Constantly looking for innovative ways to talk and write about Python • Mentoring learners • Writing about Python • Writing about technical writing