Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 23 additions & 23 deletions concepts/dict-methods/about.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
# Dictionary Methods in Python

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

- `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>.setdefault()` automatically adds keys without throwing a KeyError.
- `<dict>.fromkeys(<iterable>, <default value>)` creates a new `dict` from any number of iterables.
- `<dict>.keys()`, `<dict>.values()`, and `<dict>.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

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`.
The dictionary concept previously covered that `<dict>.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.

For a similarly "safe" (_without KeyError_) insertion operation, there is the `.setdefault(key, <default value>)` method.
`setdefault(key, <default value>)` will return the `value` if the `key` is found in the dictionary.
For a similarly "safe" (_without `KeyError`_) insertion operation, there is the `<dict>.setdefault(<key>, <default value>)` method.
`<dict>.setdefault(<key>, <default value>)` will return the `value` if the `key` is found in the dictionary.
If the key is **not** found, it will _insert_ the (`key`, `default value`) pair and return the `default value` for use.


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

Expand All @@ -38,7 +39,7 @@ If the key is **not** found, it will _insert_ the (`key`, `default value`) pair

## `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`.
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:

```python
Expand Down Expand Up @@ -71,13 +72,12 @@ If the dictionary is empty, calling `popitem()` will raise a `KeyError`:
# All (key, value) pairs have been removed.
>>> palette_I.popitem()
Traceback (most recent call last):

line 1, in <module>
palette_I.popitem()

KeyError: 'popitem(): dictionary is empty'
```


## Iterating Over Entries in a Dictionary Via Views

The `.keys()`, `.values()`, and `.items()` methods return [_iterable views_][dict-views] of a dictionary.
Expand Down Expand Up @@ -136,7 +136,7 @@ This allows keys, values, or (`key`, `value`) pairs to be iterated over in Last-
('Purple baseline', '#161748')

>>> for item in reversed(palette_II.items()):
... print (item)
... print(item)
...
('Purple baseline', '#161748')
('Green Treeline', '#478559')
Expand Down Expand Up @@ -166,12 +166,12 @@ This method will take the (`key`,`value`) pairs of `<dict_two>` and write them i
Where keys in the two dictionaries _overlap_, the `value` in `dict_one` will be _overwritten_ by the corresponding `value` from `dict_two`:

```python
>>> palette_I = {'Grassy Green': '#9bc400',
'Purple Mountains Majesty': '#8076a3',
'Misty Mountain Pink': '#f9c5bd',
'Factory Stone Purple': '#7c677f',
'Green Treeline': '#478559',
'Purple baseline': '#161748'}
>>> palette_I = {'Grassy Green': '#9bc400',
'Purple Mountains Majesty': '#8076a3',
'Misty Mountain Pink': '#f9c5bd',
'Factory Stone Purple': '#7c677f',
'Green Treeline': '#478559',
'Purple baseline': '#161748'}

>>> palette_III = {'Grassy Green': (155, 196, 0),
'Purple Mountains Majesty': (128, 118, 163),
Expand Down Expand Up @@ -333,10 +333,10 @@ If the values stored in the `dict` are not unique, extra checks become necessary

# Iterating over (key, value) pairs using .items()
>>> for key, value in extended_color_reference.items():
... if value in consolidated_colors: #Check if key has already been created.
... if value in consolidated_colors: # <--Check if key has already been created.
... consolidated_colors[value].append(key)
... else:
... consolidated_colors[value] = [key] #Create a value list with the former key in it.
... consolidated_colors[value] = [key] # <--Create a value list with the former key in it.

>>> consolidated_colors
{'Purple Mountains Majesty': ['#8076a3', (128, 118, 163), (21, 28, 0, 36)],
Expand Down
14 changes: 7 additions & 7 deletions concepts/dict-methods/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ The `dict` class in Python provides many useful [methods][dict-methods], some of

This concept tackles a few more:

- `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>.setdefault()` automatically adds keys without throwing a KeyError.
- `<dict>.fromkeys(<iterable>, <default value>)` creates a new `dict` from any number of iterables.
- `<dict>.keys()`, `<dict>.values()`, and `<dict>.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.

[dict-methods]: https://docs.python.org/3/library/stdtypes.html#dict
18 changes: 9 additions & 9 deletions concepts/sets/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
A [`set`][type-set] is a _mutable_ and _unordered_ collection of [_hashable_][hashable] objects.
Set members must be distinct — duplicate items are not allowed.
They can hold multiple different data types and even nested structures like a `tuple` of `tuples` — as long as all elements can be _hashed_.
Sets also come in an immutable [`frozensets`][type-frozenset] flavor.
Sets also come in an immutable [`frozenset`][type-frozenset] flavor.

Sets are most commonly used to quickly remove duplicates from other data structures or item groupings.
They are also used for efficient comparisons when sequencing and duplicate tracking are not needed.

Like other collection types (_dictionaries, lists, tuples_), `sets` support:
- Iteration via `for item in <set>`
- Iteration via `for item in <set>`,
- Membership checking via `in` and `not in`,
- Length calculation through `len()`, and
- Shallow copies through `copy()`
- Shallow copies through `copy()`.

`sets` do not support:
- Indexing of any kind
Expand Down Expand Up @@ -174,12 +174,12 @@ Traceback (most recent call last):

Sets have methods that generally mimic [mathematical set operations][mathematical-sets].
Most (_not all_) of these methods have an [operator][operator] equivalent.
Methods generally take any `iterable` as an argument, while operators require that both sides of the operation are `sets` or `frozensets`.
Methods generally take any `iterable` as an argument, while operators require that both sides of the operation are `set`s or `frozenset`s.


### Membership Testing Between Sets

The `<set>.isdisjoint(<other_collection>)` method is used to test if a `sets` elements have any overlap with the elements of another.
The `<set>.isdisjoint(<other_collection>)` method is used to test if a `set`'s elements have any overlap with the elements of another.
The method will accept any `iterable` or `set` as an argument.
It will return `True` if the two sets have **no elements in common**, `False` if elements are **shared**.

Expand Down Expand Up @@ -275,9 +275,9 @@ True
### 'Proper' Subsets and Supersets

`<set> < <other_set>` and `<set> > <other_set>` are used to test for _proper subsets_.
A `set` is a proper subset if (`<set>` <= `<other_set>`) **AND** (`<set>` != `<other_set>`) for the `<` operator.
A `set` is a proper subset if (`<set> <= <other_set>`) **AND** (`<set> != <other_set>`) for the `<` operator.

A `set is a proper superset if `(`<set>` >= `<other_set>`) **AND** (`<set>` != `<other_set>`) for the `>` operator.
A `set` is a proper superset if (`<set> >= <other_set>`) **AND** (`<set> != <other_set>`) for the `>` operator.
These operators have no method equivalent:

```python
Expand Down Expand Up @@ -336,7 +336,7 @@ The operator form of this method is `<set> | <other set 1> | <other set 2> | ...
### Set Differences

`<set>.difference(*<other iterables>)` returns a new `set` with elements from the original `<set>` that are not in `<others>`.
The operator version of this method is `<set> - <other set 1> - <other set 2> - ...<other set n>`.
The operator version of this method is `<set> - <other set 1> - <other set 2> - ... - <other set n>`.

```python
>>> berries_and_veggies = {'Asparagus',
Expand Down Expand Up @@ -370,7 +370,7 @@ The operator version of this method is `<set> - <other set 1> - <other set 2> -
### Set Intersections

`<set>.intersection(*<other iterables>)` returns a new `set` with elements common to the original `set` and all `<others>` (in other words, the `set` where everything [intersects][intersection]).
The operator version of this method is `<set> & <other set> & <other set 2> & ... <other set n>`
The operator version of this method is `<set> & <other set> & <other set 2> & ... & <other set n>`

```python
>>> perennials = {'Annatto','Asafetida','Asparagus','Azalea',
Expand Down
6 changes: 3 additions & 3 deletions concepts/sets/introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
A [`set`][type-set] is a _mutable_ and _unordered_ collection of [_hashable_][hashable] objects.
Set members must be distinct — duplicate items are not allowed.
They can hold multiple different data types and even nested structures like a `tuple` of `tuples` — as long as all elements can be _hashed_.
Sets also come in an immutable [`frozensets`][type-frozenset] flavor.
Sets also come in an immutable [`frozenset`][type-frozenset] flavor.

Sets are most commonly used to quickly remove duplicates from other data structures or item groupings.
They are also used for efficient comparisons when sequencing and duplicate tracking are not needed.

Like other collection types (_dictionaries, lists, tuples_), `sets` support:
- Iteration via `for item in <set>`
- Iteration via `for item in <set>`,
- Membership checking via `in` and `not in`,
- Length calculation through `len()`, and
- Shallow copies through `copy()`
- Shallow copies through `copy()`.

`sets` do not support:
- Indexing of any kind
Expand Down
Loading