diff --git a/concepts/dict-methods/about.md b/concepts/dict-methods/about.md index 02f2dc21fa..7af90a7714 100644 --- a/concepts/dict-methods/about.md +++ b/concepts/dict-methods/about.md @@ -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, )` creates a new `dict` from any number of iterables. -- `.keys()`, `.values()`, and `.items()` provide convenient iterators. -- `sorted(.items())`. can easily re-order entries in a `dict`. -- `dict_one.update()` 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. +- `.setdefault()` automatically adds keys without throwing a KeyError. +- `.fromkeys(, )` creates a new `dict` from any number of iterables. +- `.keys()`, `.values()`, and `.items()` provide convenient iterators. +- `sorted(.items())` can easily re-order entries in a `dict`. +- `.update()` updates one `dict` with overlapping values from another `dict`. +- ` | ` and ` |= ` merges or updates two `dict`s via operators. +- `reversed(.keys())`, `reversed(.values())`, or `reversed(.items())` produce _reversed_ views. - `.popitem()` removes and returns a `key`, `value` pair. ## `setdefault()` for Error-Free Insertion -The dictionary concept previously covered that `.get(key, )` 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 `.get(, )` 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, )` method. -`setdefault(key, )` will return the `value` if the `key` is found in the dictionary. +For a similarly "safe" (_without `KeyError`_) insertion operation, there is the `.setdefault(, )` method. +`.setdefault(, )` 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'} @@ -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, )`][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(, )`][fromkeys] will iterate through an iterable of `keys` and create a new `dict`. All `values` will be set to the `default value` provided: ```python @@ -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 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. @@ -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') @@ -166,12 +166,12 @@ This method will take the (`key`,`value`) pairs of `` 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), @@ -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)], diff --git a/concepts/dict-methods/introduction.md b/concepts/dict-methods/introduction.md index c15fbc113d..b1e8eb8f20 100644 --- a/concepts/dict-methods/introduction.md +++ b/concepts/dict-methods/introduction.md @@ -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, )` creates a new `dict` from any number of iterables. -- `.keys()`, `.values()`, and `.items()` provide convenient iterators. -- `sorted(.items())`. can easily re-order entries in a `dict`. -- `dict_one.update()` 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. +- `.setdefault()` automatically adds keys without throwing a KeyError. +- `.fromkeys(, )` creates a new `dict` from any number of iterables. +- `.keys()`, `.values()`, and `.items()` provide convenient iterators. +- `sorted(.items())` can easily re-order entries in a `dict`. +- `.update()` updates one `dict` with overlapping values from another `dict`. +- ` | ` and ` |= ` merges or updates two `dict`s via operators. +- `reversed(.keys())`, `reversed(.values())`, or `reversed(.items())` produce _reversed_ views. - `.popitem()` removes and returns a `key`, `value` pair. [dict-methods]: https://docs.python.org/3/library/stdtypes.html#dict diff --git a/concepts/sets/about.md b/concepts/sets/about.md index 2c011c1447..944f98d1b5 100644 --- a/concepts/sets/about.md +++ b/concepts/sets/about.md @@ -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 ` +- Iteration via `for item in `, - 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 @@ -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 `.isdisjoint()` method is used to test if a `sets` elements have any overlap with the elements of another. +The `.isdisjoint()` 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**. @@ -275,9 +275,9 @@ True ### 'Proper' Subsets and Supersets ` < ` and ` > ` are used to test for _proper subsets_. -A `set` is a proper subset if (`` <= ``) **AND** (`` != ``) for the `<` operator. +A `set` is a proper subset if (` <= `) **AND** (` != `) for the `<` operator. -A `set is a proper superset if `(`` >= ``) **AND** (`` != ``) for the `>` operator. +A `set` is a proper superset if (` >= `) **AND** (` != `) for the `>` operator. These operators have no method equivalent: ```python @@ -336,7 +336,7 @@ The operator form of this method is ` | | | ... ### Set Differences `.difference(*)` returns a new `set` with elements from the original `` that are not in ``. -The operator version of this method is ` - - - ...`. +The operator version of this method is ` - - - ... - `. ```python >>> berries_and_veggies = {'Asparagus', @@ -370,7 +370,7 @@ The operator version of this method is ` - - - ### Set Intersections `.intersection(*)` returns a new `set` with elements common to the original `set` and all `` (in other words, the `set` where everything [intersects][intersection]). -The operator version of this method is ` & & & ... ` +The operator version of this method is ` & & & ... & ` ```python >>> perennials = {'Annatto','Asafetida','Asparagus','Azalea', diff --git a/concepts/sets/introduction.md b/concepts/sets/introduction.md index 5d66b6a8ad..551e295e6a 100644 --- a/concepts/sets/introduction.md +++ b/concepts/sets/introduction.md @@ -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 ` +- Iteration via `for item in `, - 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