Skip to content

Commit a0c1eb4

Browse files
valentin-pBethanyG
authored andcommitted
Inventory Dicts Improvement (exercism#2770)
* Inventory Dicts Improvment * proofing the about file * check working * add Bethany * Update languages/concepts/dicts/about.md * Update languages/concepts/dicts/about.md Co-authored-by: BethanyG <[email protected]>
1 parent ef4e491 commit a0c1eb4

File tree

11 files changed

+168
-81
lines changed

11 files changed

+168
-81
lines changed

concepts/dicts/about.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
A dictionary in Python is a data structure that associates [hashable][term-hashable] _keys_ to _values_ and can be known in other programming languages as a [hash table or hashmap][hashtable-wikipedia]. In Python, it's considered a [mapping type][mapping-types-dict]. `dicts` enable the retrieval of a value in constant time, given the key.
2+
3+
Compared to searching for a value within a list or array (_without knowing the index position_), a dictionary uses significantly more memory, but has very rapid retrieval. It's especially useful in scenarios where the collection is large and must be accessed frequently.
4+
5+
## Keys and Values
6+
7+
A dictionary can be though of as a collection of straightforward `key`:`value` pairs. Like other collection types (`list`, `tuple`, and `set`), `values` can contain arbitrary data and data types, including nested dictionaries. A dictionary’s `keys` are _**almost**_ as arbitrary, but require their data types to be _hashable_.
8+
9+
Keys are unique across a dictionary, and the values associated with any `key` can be replaced, updated or altered as long as the `key` exists. To be a valid, a key (_and all its contained values_) must be [hashable][term-hashable]. Hashable `keys` can include numbers, strings, tuples of _immutable_ values, or frozensets. `sets`, `lists`, and `dicts` are unhashable and therefor cannot be used as keys.
10+
11+
A value can be of any data type, including built-in types, custom types or complex objects (even functions or classes). Commonly used objects are: numbers, strings, lists, dictionaries, tuples or sets.
12+
13+
A simple `dict` can be declared using the literal form `{"key_1": value_1, "key_2": value_2}` or via _constructor_ with `dict(key_1=value_1, key_2=value_2)`, but there are many more ways of creating and initializing dictionaries including the use of a _dict comprehension_ or passing additional constructor parameters as illustrated in the [Python docs][mapping-types-dict].
14+
15+
Inserting a new `key`:`value` pair can be done with `dict[key] = value` and the value can be retrieved by using `retrieved_value = dict[key]`.
16+
17+
## Methods
18+
19+
`dicts` implement various methods to allow easy initialization, updating and viewing.
20+
21+
Some useful `dict` methods:
22+
23+
- Retrieve a value "safely" from a dictionary by using the `.get(key, [default])` method. `.get(key, [default])` returns the value for the key **or** the _default value_ if the key is not found, instead of raising a `KeyError`. This works well in situations where you would rather not have extra error handling but cannot trust that a looked-for key will be present.
24+
- Retrieve a value "safely" or insert a default _value_ if the key is not found using the `.setdefault(key, [default])` method. `setdefault(key, [default])` will insert the default value in the dictionary **only** if the key is not found, then it will retrieve either the **newly inserted** default value if the key was not found or the **unchanged** existing value if the key was found.
25+
- Return various _iterable_ views of your `dict` with `.keys()`, `.values()`, `.items()` (_an iterable of (key, value) `tuples`_).
26+
27+
For a detailed explanation of dictionaries in Python, the [official documentation][dicts-docs] is an excellent starting place, or you can also check out the [W3-Schools][how-to-dicts] tutorial.
28+
29+
## Extending Dictionaries: The collections module
30+
31+
The [`collections`][collections-docs] module adds more functionality to Python's standard collection-based datatypes (`dictionary`, `set`, `list`, `tuple`). A popular `dict`-oriented member of this module is the [`Counter`][counter-dicts], which automatically counts items and returns them a `dict` with the items as keys and their counts as values. There is also the [`OrderedDict`][ordered-dicts-docs], which has methods specialized for re-arranging the order of a dictionary. Finally, there is the [`defaultdict`][default-dicts], a subclass of the built-in `dict` module that, based on a factory method, sets a default value if a key is not found when trying to retrieve or assign the value.
32+
33+
[term-hashable]: https://docs.python.org/3/glossary.html#term-hashable
34+
[hashtable-wikipedia]: https://en.wikipedia.org/wiki/Hash_table
35+
[mapping-types-dict]: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
36+
[dicts-docs]: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
37+
[how-to-dicts]: https://www.w3schools.com/python/python_dictionaries.asp
38+
[collections-docs]: https://docs.python.org/3/library/collections.html
39+
[counter-dicts]: https://docs.python.org/3/library/collections.html#collections.Counter
40+
[ordered-dicts-docs]: https://docs.python.org/3/library/collections.html#collections.OrderedDict
41+
[default-dicts]: https://docs.python.org/2/library/collections.html#collections.defaultdict

concepts/dicts/links.json

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
[
2+
{
3+
"url": "https://docs.python.org/3/glossary.html#term-hashable",
4+
"description": "term-hashable"
5+
},
6+
{
7+
"url": "https://docs.python.org/3/library/stdtypes.html#mapping-types-dict",
8+
"description": "mapping-types-dict"
9+
},
10+
{
11+
"url": "https://docs.python.org/3/tutorial/datastructures.html#dictionaries",
12+
"description": "dicts-docs"
13+
},
14+
{
15+
"url": "https://www.w3schools.com/python/python_dictionaries.asp",
16+
"description": "how-to"
17+
},
18+
{
19+
"url": "https://docs.python.org/3/library/collections.html",
20+
"description": "collections-docs"
21+
},
22+
{
23+
"url": "https://docs.python.org/3/library/collections.html#collections.Counter",
24+
"description": "counter-dicts"
25+
},
26+
{
27+
"url": "https://docs.python.org/3/library/collections.html#collections.OrderedDict",
28+
"description": "ordered-dicts-docs"
29+
},
30+
{
31+
"url": "https://docs.python.org/2/library/collections.html#collections.defaultdict",
32+
"description": "default-dicts"
33+
}
34+
]

exercises/concept/inventory-management/.docs/after.md

Lines changed: 0 additions & 22 deletions
This file was deleted.
Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,28 @@
1-
# TO DO
1+
## General
2+
3+
- [The Python Dictionary Tutorial](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) can be a great introduction.
4+
5+
## 1. Create the dictionary
6+
7+
- You need a [for loop](https://docs.python.org/3/tutorial/controlflow.html#for-statements) to iterate the list of items, then insert each item in the dictionary if missing and increment the item count using the dictionary accessor.
8+
- You can use [`setdefault`](https://www.w3schools.com/python/ref_dictionary_setdefault.asp) to make sure the value is set before incrementing the count of the item.
9+
- This function should [return a dict](https://www.w3schools.com/python/ref_keyword_return.asp).
10+
11+
## 2. Add items to a dictionary
12+
13+
- You need a [for loop](https://docs.python.org/3/tutorial/controlflow.html#for-statements) to iterate the list of items, then insert each item if not already in the dictionary and [increment](https://www.w3schools.com/python/gloss_python_assignment_operators.asp) the item count using the dictionary accessor.
14+
- You can use [`setdefault`](https://www.w3schools.com/python/ref_dictionary_setdefault.asp) to make sure the value is set before incrementing the count of the item.
15+
- The function `add_items` can be used by the `create_inventory` function with an empty dictionary in parameter.
16+
- This function should [return a dict](https://www.w3schools.com/python/ref_keyword_return.asp).
17+
18+
## 3. Delete items from a dictionary
19+
20+
- You need [for loop](https://docs.python.org/3/tutorial/controlflow.html#for-statements) to iterate the list of items, if the number of items is not `0` then [decrement](https://www.w3schools.com/python/gloss_python_assignment_operators.asp) the current number of items.
21+
- You can use the `key in dict` that returns `True` if the key exists to make sure the value is in the dictionary before decrementing the number of items.
22+
- This function should [return a dict](https://www.w3schools.com/python/ref_keyword_return.asp).
23+
24+
## 4. List the items that are in stock
25+
26+
- You need [for loop](https://docs.python.org/3/tutorial/controlflow.html#for-statements) on the inventory and if the number of item is greater of `0` then append the tuple to a list.
27+
- You can use `dict.items()` to iterate on both the item and the value at the same time, `items()` returns a tuple that you can use as it is or deconstruct.
28+
- This function should [return](https://www.w3schools.com/python/ref_keyword_return.asp) a [list](https://docs.python.org/3/tutorial/introduction.html#lists) of [tuples](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences).
Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1-
In this exercise you'll be managing an inventory system.
1+
In this exercise, you will be managing an inventory system.
22

3-
You will be given a list of items. Each time an item is in the given list, add `1` to the key in the _given_ inventory. Each item should be organized by their name and the amount of that item. You will also have to delete items from the inventory.
3+
The inventory should be organized by the item name and it should keep track of the number of items available.
44

5-
You will also have to implement a function which returns a list of `tuples` of all the key-value pairs in the _given_ inventory.
5+
You will have to handle adding items to an inventory. Each time an item appears in a given list, increase the item's quantity by `1` in the inventory. Then, you will have to handle deleting items from an inventory.
66

7-
## 1. Create an inventory from a list
7+
To finish, you will have to implement a function which returns all the key-value pairs in an inventory as a list of `tuples`.
88

9-
Implement the `create_inventory()` function that creates an "inventory" from a list of items. It should return a `dictionary` representing the types and amounts of the items.
9+
## 1. Create an inventory based on a list
10+
11+
Implement the `create_inventory()` function that creates an "inventory" from a list of items. It should return a `dict` containing each item name paired with their respective quantity.
1012

1113
```python
1214
>>> create_inventory(["coal", "wood", "wood", "diamond", "diamond", "diamond"])
@@ -15,7 +17,7 @@ Implement the `create_inventory()` function that creates an "inventory" from a l
1517

1618
## 2. Add items from a list to an existing dictionary
1719

18-
Implement the `add_items()` function that adds a list of items to a passed in inventory dictionary:
20+
Implement the `add_items()` function that adds a list of items to an inventory:
1921

2022
```python
2123
>>> add_items({"coal":1}, ["wood", "iron", "coal", "wood"])
@@ -24,14 +26,14 @@ Implement the `add_items()` function that adds a list of items to a passed in in
2426

2527
## 3. Remove items from the inventory
2628

27-
Implement the `delete_items()` function that removes items in the passed-in list from the passed inventory dictionary:
29+
Implement the `delete_items()` function that removes every item in the list from an inventory:
2830

2931
```python
3032
>>> delete_items({"coal":3, "diamond":1, "iron":5}, ["diamond", "coal", "iron", "iron"])
3133
{"coal":2, "diamond":0, "iron":3}
3234
```
3335

34-
Item counts should not fall below `0`, if the amount of an item in the list exceeds the amount of items in the inventory, the value should stop at `0` and not go into negative numbers.
36+
Item counts should not fall below `0`, if the number of items in the list exceeds the number of items available in the inventory, the listed quantity for that item should remain at `0` and the request for removing that item should be ignored.
3537

3638
```python
3739
>>> delete_items({"coal":2, "wood":1, "diamond":2}, ["coal", "coal", "wood", "wood", "diamond"])
@@ -40,9 +42,9 @@ Item counts should not fall below `0`, if the amount of an item in the list exce
4042

4143
## 4. Return the inventory content
4244

43-
Implement the `list_inventory()` function that takes an inventory and returns a list of `(item, amount)` tuples. Only include items where the amount is greater than zero:
45+
Implement the `list_inventory()` function that takes an inventory and returns a list of `(item, quantity)` tuples. The list should only include the available items (with a quantity greater than zero):
4446

4547
```python
46-
>>> list_inventory({"coal":7, "wood":11, "diamond":2, "iron":7, "silver": 0})
48+
>>> list_inventory({"coal":7, "wood":11, "diamond":2, "iron":7, "silver":0})
4749
[('coal', 7), ('diamond', 2), ('iron', 7), ('wood', 11)]
4850
```
Lines changed: 21 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,65 @@
11
## dicts
22

3-
A _dictionary_ is Python's primary mapping type that connects _hashable keys_ with values. The looking up of keys is more efficient than searching through an array, but does require more memory.
3+
A _**dictionary**_ is Python's primary mapping type that associates a _hashable key_ with a value. The lookup by key is more efficient than searching through an array, but does require more memory.
44

55
## Dict construction
66

7-
Dictionaries can be created in various ways. You can either use the `dict()` class constructor or the literal declaration of a _dict_.
7+
Dictionaries can be created in various ways. Two simple options are the use the `dict()` class constructor or the dict literal declaration with key-value pairs.
88

99
### Use the `dict()` constructor
1010

1111
```python
12-
>>> bear = dict(name="Black Bear", amount=5, land_animal=True)
13-
{'name': 'Panda', 'amount': 15, 'land_animal': True}
12+
>>> bear = dict(name="Black Bear", speed=40, land_animal=True)
13+
{'name': 'Black Bear', 'speed': 40, 'land_animal': True}
1414
```
1515

1616
### Declare a _dict_ literal
1717

1818
```python
19-
>>> whale = {"name":"Blue Whale", "amount":2, "land_animal":False}
20-
{'name': 'Dolphin', 'amount': 2, 'land_animal': False}
19+
>>> whale = {"name": "Blue Whale", "speed": 35, "land_animal": False}
20+
{'name': 'Blue Whale', 'speed': 35, 'land_animal': False}
2121
```
2222

23-
With literal declaration keep in mind that _keys_ are replaced with _data types_ and the `=` is replaced with a `:`.
23+
With the dict literal declaration keep in mind that _keys_ are of _data types_ `str` and the colon `:` is used instead of an equal sign `=`.
2424

2525
## Accessing values
2626

27-
You can access items in a dictionary in two ways, using the _key_ of the value.
27+
You can access an item in a dictionary using the _key_ of the value.
2828

2929
### Using _square brackets_ after the dict object
3030

3131
```python
32-
>>> request_brackets = bear["amount"]
33-
5
32+
>>> bear["speed"]
33+
40
3434
```
3535

3636
### Using `.get()`
3737

3838
```python
39-
>>> request_get = whale.get("name")
40-
Blue Whale
39+
>>> whale.get("name")
40+
'Blue Whale'
4141
```
4242

4343
## Changing values
4444

45-
You can easily change a value of an item using it's _key_.
45+
You can easily change a value of an item using its _key_.
4646

4747
```python
4848
>>> bear["name"] = "Grizzly Bear"
49-
{'name': 'Grizzly Bear', 'amount': 5, 'land_animal': True}
49+
{'name': 'Grizzly Bear', 'speed': 40, 'land_animal': True}
5050

51-
>>> whale["amount"] = 7
52-
{'name': 'Blue Whale', 'amount': 7, 'land_animal': False}
51+
>>> whale["speed"] = 25
52+
{'name': 'Blue Whale', 'speed': 25, 'land_animal': False}
5353
```
5454

5555
## Looping through a dictionary
5656

57-
Looping through a dictionary using a `for` loop only returns the _keys_ of the items.
57+
Looping through a dictionary using `for item in dict` will iterate over the _keys_, but you can access the _values_ by using _square brackets_.
5858

5959
```python
6060
>>> for key in bear:
61-
>>> print(key)
62-
name
63-
amount
64-
land_animal
65-
```
66-
67-
But you can also make a `for` loop return the _values_ of a dictionary with a simple trick.
68-
69-
```python
70-
>>> for key in whale:
71-
>>> print(whale[key])
72-
Blue Whale
73-
7
74-
False
61+
>>> (key, bear[key])
62+
('name', 'Black Bear')
63+
('speed', 40)
64+
('land_animal', True)
7565
```

exercises/concept/inventory-management/.meta/config.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@
55
"exercism_username": "j08k"
66
}
77
],
8+
"contributors": [
9+
{
10+
"github_username": "valentin-p",
11+
"exercism_username": "valentin-p"
12+
},
13+
{
14+
"github_username": "bethanyG",
15+
"exercism_username": "bethanyG"
16+
}
17+
],
818
"editor": {
919
"solution_files": ["dicts.py"],
1020
"test_files": ["dicts_test.py"]

exercises/concept/inventory-management/.meta/design.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
The goal of this exercise is to teach the basics of the `dict` (dictionary, mapping) data type in Python.
66

7-
## Things to teach
7+
## Learning objectives
88

99
- create a `dict` via constructor and literal.
1010
- access values in a `dict` via `keys`.
@@ -15,7 +15,7 @@ The goal of this exercise is to teach the basics of the `dict` (dictionary, mapp
1515
- iterate through a `dict` using `dict.keys()`, `dict.values()`, or `dict.items()`.
1616
- `dict` method `setdefault()`
1717

18-
## Things not to teach
18+
## Out of scope
1919

2020
- Dictionary comprehensions
2121
- `dict` methods such as `get()` or `clear()`.

exercises/concept/inventory-management/.meta/example.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ def add_items(inventory, items):
1313

1414
def delete_items(inventory, items):
1515
for item in items:
16-
inventory.setdefault(item, 0)
17-
inventory[item] = max(inventory[item] - 1, 0)
16+
if item in inventory:
17+
inventory[item] = max(inventory[item] - 1, 0)
1818
return inventory
1919

2020

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
def create_inventory(items):
22
pass
33

4+
45
def add_items(inventory, items):
56
pass
67

8+
79
def delete_items(inventory, items):
810
pass
911

12+
1013
def list_inventory(inventory):
1114
pass

0 commit comments

Comments
 (0)