Skip to content

Commit

Permalink
Concept tidy-up and typo fixes.
Browse files Browse the repository at this point in the history
  • Loading branch information
BethanyG committed Jul 5, 2023
1 parent bfad7ef commit 4206810
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 125 deletions.
79 changes: 34 additions & 45 deletions concepts/dict-methods/about.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
# Dictionary Methods in Python

A dictionary (`dict`) in Python is a data structure that associates [hashable][term-hashable] _keys_ to _values_ and is known in other programming languages as a resizable [hash table][hashtable-wikipedia], hashmap, or [associative array][associative-array].
Dictionaries are Python's only built-in [mapping type][mapping-types-dict].
As of Python 3.7, `dict` key order is guaranteed to be the order in which entries are inserted.

Given a `key`, dictionaries can retrieve a `value` in (on average) constant time (_independent of the number of entries_).
Compared to searching for a value within a `list` or `array` (_without knowing the `index` position_), a `dict` uses significantly more memory, but has very rapid retrieval.
Dictionaries are especially useful in scenarios where the collection of items is large and must be accessed and updated frequently.

## Dictionary Methods

The `dict` class in Python provides many useful [methods][dict-methods] for working with dictionaries.
Some were introduced in the concept for `dicts`.
Here we cover a few more - along with some techniques for iterating through and manipulating dictionaries.

- `dict.setdefault()` for automatically adding keys without error.
- `dict.fromkeys(iterable, <default value>)` for creating a new `dict` from any number of iterables.
- `.keys()`, `.values()`, and `.items()` for convenient iterators.
- `sorted(<dict>.items())`. for re-ordering entries in a `dict`.
- `dict_one.update(<dict_two>)` for updating one `dict` with overlapping values from another `dict`.
- `dict | other_dict` and `dict |= other_dict` for merging or updating two `dict`s via operators.
- `reversed(dict.keys())`, `reversed(dict.values())`, or `reversed(dict.items())` for reversed views.
- `<dict>.popitem()` for removing and returning a `key`, `value` pair.
- `dict.setdefault()` automatically adds keys without throwing a KeyError.
- `dict.fromkeys(iterable, <default value>)` creates a new `dict` from any number of iterables.
- `.keys()`, `.values()`, and `.items()` provide convenient iterators.
- `sorted(<dict>.items())`. can easily re-order entries in a `dict`.
- `dict_one.update(<dict_two>)` updates one `dict` with overlapping values from another `dict`.
- `dict | other_dict` and `dict |= other_dict` merges or updates two `dict`s via operators.
- `reversed(dict.keys())`, `reversed(dict.values())`, or `reversed(dict.items())` produce _reversed_ views.
- `<dict>.popitem()` removes and returns a `key`, `value` pair.

### `setdefault()` for Error-Free Insertion

## `setdefault()` for Error-Free Insertion

The dictionary concept previously covered that `.get(key, <default value>)` returns an existing `value` or the `default value` if a `key` is not found in a dictionary, thereby avoiding 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.
Expand All @@ -35,18 +26,17 @@ If the key is **not** found, it will _insert_ the (`key`, `default value`) pair
```python
>>> palette_I = {'Grassy Green': '#9bc400', 'Purple Mountains Majesty': '#8076a3', 'Misty Mountain Pink': '#f9c5bd'}

#Looking for the value associated with key "Rock Brown".
#The key does not exist, so it is added with the default
# value, and the value is returned.
# Looking for the value associated with key "Rock Brown".The key does not exist,
# so it is added with the default value, and the value is returned.
>>> palette.setdefault('Rock Brown', '#694605')
'#694605'

#The (key, default value) pair has now been added to the dictionary.
# The (key, default value) pair has now been added to the dictionary.
>>> palette_I
{'Grassy Green': '#9bc400', 'Purple Mountains Majesty': '#8076a3', 'Misty Mountain Pink': '#f9c5bd', 'Rock Brown': '#694605'}
```

### Use `fromkeys()` to Populate a Dictionary
## `fromkeys()` to Populate a Dictionary from an Iterable

To quickly populate a dictionary with various `keys` and default values, the _class method_ [`fromkeys(iterable, <default value>)`][fromkeys] will iterate through an iterable of `keys` and create a new `dict`.
All `values` will be set to the `default value` provided:
Expand All @@ -59,7 +49,7 @@ All `values` will be set to the `default value` provided:
'Misty Mountain Pink': 'fill in hex color here'}
```

### Removing and Returning a (key, value) Pair With `.popitem()`
## Remove and Return a (key, value) Pair With `.popitem()`

`.popitem()` removes & returns a single (`key`, `value`) pair from a dictionary.
Pairs are returned in Last-in-First-out (`LIFO`) order.
Expand All @@ -78,7 +68,7 @@ If the dictionary is empty, calling `popitem()` will raise a `KeyError`:
>>> palette_I.popitem()
('Grassy Green', '#9bc400')

#All (key, value) pairs have been removed.
# All (key, value) pairs have been removed.
>>> palette_I.popitem()
Traceback (most recent call last):

Expand All @@ -88,30 +78,31 @@ Traceback (most recent call last):
KeyError: 'popitem(): dictionary is empty'
```

### Iterating Over Entries in a Dictionary
## Iterating Over Entries in a Dictionary Via Views

The `.keys()`, `.values()`, and `.items()` methods return [_iterable views_][dict-views] of a dictionary.
These views can be used for looping over entries without altering them.
They are also _dynamic_ -- when underlying dictionary data changes, the associated view object will reflect the change:

These views can be used to easily loop over entries without altering them.
Views are also _dynamic_ -- when underlying dictionary data changes, the associated `view object` will reflect the change:

```python
>>> palette_I = {'Grassy Green': '#9bc400',
'Purple Mountains Majesty': '#8076a3',
'Misty Mountain Pink': '#f9c5bd'}

#Using .keys() returns a list of keys.
# Using .keys() returns a list of keys.
>>> palette_I.keys()
dict_keys(['Grassy Green', 'Purple Mountains Majesty', 'Misty Mountain Pink'])

#Using .values() returns a list of values.
# Using .values() returns a list of values.
>>> palette_I.values()
dict_values(['#9bc400', '#8076a3', '#f9c5bd'])

#Using .items() returns a list of (key, value) tuples.
# Using .items() returns a list of (key, value) tuples.
>>> palette_I.items()
dict_items([('Grassy Green', '#9bc400'), ('Purple Mountains Majesty', '#8076a3'), ('Misty Mountain Pink', '#f9c5bd')])

#Views are dynamic. Changing values in the dict
# Views are dynamic. Changing values in the dict
# changes all of the associated views.
>>> palette_I['Purple Mountains Majesty'] = (128, 118, 163)
>>> palette_I['Deep Red'] = '#932432'
Expand All @@ -126,11 +117,12 @@ dict_keys(['Grassy Green', 'Purple Mountains Majesty', 'Misty Mountain Pink', 'D
dict_items([('Grassy Green', '#9bc400'), ('Purple Mountains Majesty', (128, 118, 163)), ('Misty Mountain Pink', '#f9c5bd'), ('Deep Red', '#932432')])
```

### More on `.keys()`, `.values()`, and `.items()`
## More on `.keys()`, `.values()`, and `.items()`

In Python 3.7+, `dicts` preserve the order in which entries are inserted allowing First-in, First-out (_`FIFO`_), iteration when using `.keys()`, `.values()`, or `.items()`.

In Python 3.7+, `dicts` preserve the order in which entries are inserted allowing First-in, First-out (_`FIFO`_), iteration using `.keys()`, `.values()`, or `.items()`.
In Python 3.8+, views are also _reversible_.
This allows keys, values, or (key, value) pairs to be iterated over in Last-in, First-out (`LIFO`) order by using `reversed(<dict>.keys())`, `reversed(<dict>.values())`, or `reversed(<dict>.items())`:
This allows keys, values, or (`key`, `value`) pairs to be iterated over in Last-in, First-out (`LIFO`) order by using `reversed(<dict>.keys())`, `reversed(<dict>.values())`, or `reversed(<dict>.items())`:

```python
>>> palette_II = {'Factory Stone Purple': '#7c677f',
Expand All @@ -151,7 +143,7 @@ This allows keys, values, or (key, value) pairs to be iterated over in Last-in,
('Factory Stone Purple', '#7c677f')
```

### Combining Dictionaries with `.update()`
## Combine Dictionaries with `.update()`

`<dict_one>.update(<dict_two>)` can be used to _combine_ two dictionaries.
This method will take the (`key`,`value`) pairs of `<dict_two>` and write them into `<dict_one>`:
Expand All @@ -166,7 +158,7 @@ This method will take the (`key`,`value`) pairs of `<dict_two>` and write them i

>>> palette_I.update(palette_II)

#Note that new items from palette_II are added.
# Note that new items from palette_II are added.
>>> palette_I
{'Grassy Green': '#9bc400', 'Purple Mountains Majesty': '#8076a3', 'Misty Mountain Pink': '#f9c5bd', 'Factory Stone Purple': '#7c677f', 'Green Treeline': '#478559', 'Purple Baseline': '#161748'}
```
Expand All @@ -186,7 +178,7 @@ Where keys in the two dictionaries _overlap_, the `value` in `dict_one` will be
'Misty Mountain Pink': (249, 197, 189)}
>>> palette_I.update(palette_III)

#Overlapping values in palette_I are replaced with
# Overlapping values in palette_I are replaced with
# values from palette_III
>>> palette_I
{'Grassy Green': (155, 196, 0),
Expand All @@ -196,7 +188,7 @@ Where keys in the two dictionaries _overlap_, the `value` in `dict_one` will be
'Green Treeline': '#478559', 'Purple baseline': '#161748'}
```

### Merging and Updating Dictionaries Via the Union (`|`) Operators
## Merge or Update Dictionaries Via the Union (`|`) Operators

Python 3.9 introduces a different means of merging `dicts`: the `union` operators.
`dict_one | dict_two` will create a **new dictionary**, made up of the (`key`, `value`) pairs of `dict_one` and `dict_two`.
Expand Down Expand Up @@ -239,7 +231,7 @@ When both dictionaries share keys, `dict_two` values take precedence.
'Purple baseline': '#161748'}
```

### Sorting a Dictionary
## Sorting a Dictionary

Dictionaries do not have a built-in sorting method.
However, it is possible to sort a `dict` _view_ using the built-in function `sorted()` with `.items()`.
Expand Down Expand Up @@ -279,7 +271,7 @@ Unless a _sort key_ is specified, the default sort is over dictionary `keys`.
'Misty Mountain Pink': '#f9c5bd'}
```

### Transposing a Dictionaries Keys and Values
## Transposing a Dictionaries Keys and Values

Swapping keys and values reliably in a dictionary takes a little work, but can be accomplished via a `loop` using `dict.items()` or in a dictionary comprehension.
Safe swapping assumes that `dict` keys and values are both _hashable_.
Expand Down Expand Up @@ -359,14 +351,11 @@ For a detailed explanation of dictionaries and methods for working with them, th

For more on sorting, see the [Sorting HOW TO][sorting-howto] in the Python docs.

[associative-array]: https://en.wikipedia.org/wiki/Associative_array#:~:text=In%20computer%20science%2C%20an%20associative,a%20function%20with%20finite%20domain.
[dict-methods]: https://docs.python.org/3/library/stdtypes.html#dict
[dict-views]: https://docs.python.org/3/library/stdtypes.html#dict-views
[dicts-docs]: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
[fi-dict-guide]: https://blog.finxter.com/python-dictionary
[fromkeys]: https://docs.python.org/3/library/stdtypes.html#dict.fromkeys
[hashtable-wikipedia]: https://en.wikipedia.org/wiki/Hash_table
[how-to-dicts]: https://www.w3schools.com/python/python_dictionaries.asp
[mapping-types-dict]: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
[sorting-howto]: https://docs.python.org/3/howto/sorting.html
[term-hashable]: https://docs.python.org/3/glossary.html#term-hashable
27 changes: 8 additions & 19 deletions concepts/dict-methods/introduction.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,16 @@
# Dictionary Methods in Python

A dictionary (`dict`) in Python is a data structure that associates [hashable][term-hashable] _keys_ to _values_ and is known in other programming languages as a resizable [hash table][hashtable-wikipedia], hashmap, or [associative array][associative-array].
Dictionaries are Python's only built-in [mapping type][mapping-types-dict].
As of Python 3.7, `dict` key order is guaranteed to be the order in which entries are inserted.

Given a `key`, dictionaries can retrieve a `value` in (on average) constant time (_independent of the number of entries_).
Compared to searching for a value within a `list` or `array` (_without knowing the `index` position_), a `dict` uses significantly more memory, but has very rapid retrieval.
Dictionaries are especially useful in scenarios where the collection of items is large and must be accessed and updated frequently.
The `dict` class in Python provides many useful [methods][dict-methods], some of which are introduced in the concept exercise for dictionaries.

This concept tackles a few more:

- `dict.setdefault()` for automatically adding keys when needed.
- `dict.fromkeys(iterable, <default value>)` for creating a new `dict` from any number of iterables.
- `.keys()`, `.values()`, and `.items()` for convenient iterators.
- `sorted(<dict>.items())`. for re-ordering entries in a `dict`.
- `dict_one.update(<dict_two>)` for updating one `dict` with overlapping values from another `dict`.
- `dict | other_dict` and `dict |= other_dict` for merging or updating two `dict`s via operators.
- `reversed(dict.keys())`, `reversed(dict.values())`, or `reversed(dict.items())` for reversed views.
- `<dict>.popitem()` for removing and returning a `key`, `value` pair.
- `dict.setdefault()` automatically adds keys without throwing a `KeyError`.
- `dict.fromkeys(iterable, <default value>)` creates a new `dict` from any number of iterables.
- `.keys()`, `.values()`, and `.items()` provide convenient iterators.
- `sorted(<dict>.items())`. can easily re-order entries in a `dict`.
- `dict_one.update(<dict_two>)` updates one `dict` with overlapping values from another `dict`.
- `dict | other_dict` and `dict |= other_dict` merges or updates two `dict`s via operators.
- `reversed(dict.keys())`, `reversed(dict.values())`, or `reversed(dict.items())` produce _reversed_ views.
- `<dict>.popitem()` removes and returns a `key`, `value` pair.

[associative-array]: https://en.wikipedia.org/wiki/Associative_array#:~:text=In%20computer%20science%2C%20an%20associative,a%20function%20with%20finite%20domain.
[mapping-types-dict]: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
[hashtable-wikipedia]: https://en.wikipedia.org/wiki/Hash_table
[term-hashable]: https://docs.python.org/3/glossary.html#term-hashable
[dict-methods]: https://docs.python.org/3/library/stdtypes.html#dict
Loading

0 comments on commit 4206810

Please sign in to comment.