From fb9b6f57f30c9e038afebcdf8d638e7309b74563 Mon Sep 17 00:00:00 2001 From: waldek Date: Tue, 9 Nov 2021 11:42:48 +0100 Subject: [PATCH] adds dicts --- learning_python3.md | 109 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 106 insertions(+), 3 deletions(-) diff --git a/learning_python3.md b/learning_python3.md index ded8655..4ca8ae1 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -1623,15 +1623,98 @@ Don't just copy this code, read it and recreate it yourself! Once the library is done you can code the *interface*. For some inspiration for a simple question/response system you can have a look [here](./assets/pwd_cli.py). - # Dictionaries as data containers -TODO adapt the login generator to output a dict +Of the *built-in* types we first say `str`, `int` and `float`. +Next we saw *sequence* types such as `list` and `tupple`. +Now we'll dive into a **mapping type** called `dict`. +I advise you to have a look at the [reference pages](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) when in doubt. + +A dictionary is *kind* of like a list but it has **two** objects per **element**. +We call them **key** and **value**. +There are a couple of rules you need to be aware of though. + +1. In a `dict` the keys have to be **unique**. +2. A dictionary is **unordered** meaning the *first* element is not garanteed to remain the first over the lifespan of the dictionary. +3. The keys used must be **hashable**. + +Let's visualize a legal dictionary! +It's declared with **curly brackets** as follows `{}`. + +```python3 +my_data = {"key": "value", "name": "wouter", "age": 35} + +same_data_different_layout = { + "key": "value", + "name": "wouter", + "age": 35, + } +``` + +Let's have a look at the **methods** we can invoke on a `dict`. + +```python3 +>>> my_data = {"key": "value", "name": "wouter", "age": 35,} +>>> my_data. +my_data.clear( my_data.get( my_data.pop( my_data.update( +my_data.copy( my_data.items( my_data.popitem( my_data.values( +my_data.fromkeys( my_data.keys( my_data.setdefault( +>>> my_data.keys() +dict_keys(['key', 'name', 'age']) +>>> my_data.values() +dict_values(['value', 'wouter', 35]) +>>> my_data.items() +dict_items([('key', 'value'), ('name', 'wouter'), ('age', 35)]) +>>> for key, value in my_data.items(): +... print("key is {}".format(key)) +... print("value is {}".format(value)) +... +key is key +value is value +key is name +value is wouter +key is age +value is 35 +>>> +``` + +We can reference specific **values** corresponding to specific **keys** as follows. + +```pythons +>>> my_data["name"] +'wouter' +>>> my_data["age"] +35 +>>> +``` + +We can use dictionaries as data containers and put them in a list to group together similar data elements. +The code below should explain it quite nicely. + +```python3 +login_ovh = {"username": "EarnestCrocodile", "password": ":sdGV&[FDYZZ|RXUpZeo`J&t@*Z>^fEW"} +login_mailbox = {"username": "AbstractedDragon", "password": "32hz5&C@