You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
-[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).
In this exercise you'll be managing an inventory system.
1
+
In this exercise, you will be managing an inventory system.
2
2
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 inventoryshould be organized by the item name and it should keep track of the number of items available.
4
4
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.
6
6
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`.
8
8
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.
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.
@@ -40,9 +42,9 @@ Item counts should not fall below `0`, if the amount of an item in the list exce
40
42
41
43
## 4. Return the inventory content
42
44
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):
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.
4
4
5
5
## Dict construction
6
6
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.
0 commit comments