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
Copy file name to clipboardExpand all lines: concepts/dict-methods/about.md
+23-23Lines changed: 23 additions & 23 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,28 +1,29 @@
1
1
# Dictionary Methods in Python
2
2
3
3
The `dict` class in Python provides many useful [methods][dict-methods] for working with dictionaries.
4
-
Some were introduced in the concept for `dicts`.
4
+
Some were introduced in the concept for `dict`s.
5
5
Here we cover a few more - along with some techniques for iterating through and manipulating dictionaries.
6
6
7
-
-`dict.setdefault()` automatically adds keys without throwing a KeyError.
8
-
-`dict.fromkeys(iterable, <default value>)` creates a new `dict` from any number of iterables.
9
-
-`.keys()`, `.values()`, and `.items()` provide convenient iterators.
10
-
-`sorted(<dict>.items())`. can easily re-order entries in a `dict`.
11
-
-`dict_one.update(<dict_two>)` updates one `dict` with overlapping values from another `dict`.
12
-
-`dict | other_dict` and `dict |= other_dict` merges or updates two `dict`s via operators.
13
-
-`reversed(dict.keys())`, `reversed(dict.values())`, or `reversed(dict.items())` produce _reversed_ views.
7
+
-`<dict>.setdefault()` automatically adds keys without throwing a KeyError.
8
+
-`<dict>.fromkeys(<iterable>, <default value>)` creates a new `dict` from any number of iterables.
9
+
-`<dict>.keys()`, `<dict>.values()`, and `<dict>.items()` provide convenient iterators.
10
+
-`sorted(<dict>.items())` can easily re-order entries in a `dict`.
11
+
-`<dict_one>.update(<dict_two>)` updates one `dict` with overlapping values from another `dict`.
12
+
-`<dict> | <other_dict>` and `<dict> |= <other_dict>` merges or updates two `dict`s via operators.
13
+
-`reversed(<dict>.keys())`, `reversed(<dict>.values())`, or `reversed(<dict>.items())` produce _reversed_ views.
14
14
-`<dict>.popitem()` removes and returns a `key`, `value` pair.
15
15
16
16
17
17
## `setdefault()` for Error-Free Insertion
18
18
19
-
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`.
19
+
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`.
20
20
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.
21
21
22
-
For a similarly "safe" (_without KeyError_) insertion operation, there is the `.setdefault(key, <default value>)` method.
23
-
`setdefault(key, <default value>)` will return the `value` if the `key` is found in the dictionary.
22
+
For a similarly "safe" (_without `KeyError`_) insertion operation, there is the `<dict>.setdefault(<key>, <default value>)` method.
23
+
`<dict>.setdefault(<key>, <default value>)` will return the `value` if the `key` is found in the dictionary.
24
24
If the key is **not** found, it will _insert_ the (`key`, `default value`) pair and return the `default value` for use.
@@ -38,7 +39,7 @@ If the key is **not** found, it will _insert_ the (`key`, `default value`) pair
38
39
39
40
## `fromkeys()` to Populate a Dictionary from an Iterable
40
41
41
-
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`.
42
+
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`.
42
43
All `values` will be set to the `default value` provided:
43
44
44
45
```python
@@ -71,13 +72,12 @@ If the dictionary is empty, calling `popitem()` will raise a `KeyError`:
71
72
# All (key, value) pairs have been removed.
72
73
>>> palette_I.popitem()
73
74
Traceback (most recent call last):
74
-
75
75
line 1, in<module>
76
76
palette_I.popitem()
77
-
78
77
KeyError: 'popitem(): dictionary is empty'
79
78
```
80
79
80
+
81
81
## Iterating Over Entries in a Dictionary Via Views
82
82
83
83
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-
136
136
('Purple baseline', '#161748')
137
137
138
138
>>>for item inreversed(palette_II.items()):
139
-
...print(item)
139
+
...print(item)
140
140
...
141
141
('Purple baseline', '#161748')
142
142
('Green Treeline', '#478559')
@@ -166,12 +166,12 @@ This method will take the (`key`,`value`) pairs of `<dict_two>` and write them i
166
166
Where keys in the two dictionaries _overlap_, the `value` in `dict_one` will be _overwritten_ by the corresponding `value` from `dict_two`:
167
167
168
168
```python
169
-
>>> palette_I ={'Grassy Green': '#9bc400',
170
-
'Purple Mountains Majesty': '#8076a3',
171
-
'Misty Mountain Pink': '#f9c5bd',
172
-
'Factory Stone Purple': '#7c677f',
173
-
'Green Treeline': '#478559',
174
-
'Purple baseline': '#161748'}
169
+
>>> palette_I = {'Grassy Green': '#9bc400',
170
+
'Purple Mountains Majesty': '#8076a3',
171
+
'Misty Mountain Pink': '#f9c5bd',
172
+
'Factory Stone Purple': '#7c677f',
173
+
'Green Treeline': '#478559',
174
+
'Purple baseline': '#161748'}
175
175
176
176
>>> palette_III = {'Grassy Green': (155, 196, 0),
177
177
'Purple Mountains Majesty': (128, 118, 163),
@@ -333,10 +333,10 @@ If the values stored in the `dict` are not unique, extra checks become necessary
333
333
334
334
# Iterating over (key, value) pairs using .items()
335
335
>>>for key, value in extended_color_reference.items():
336
-
...if value in consolidated_colors: #Check if key has already been created.
336
+
...if value in consolidated_colors: # <--Check if key has already been created.
337
337
... consolidated_colors[value].append(key)
338
338
...else:
339
-
... consolidated_colors[value] = [key] #Create a value list with the former key in it.
339
+
... consolidated_colors[value] = [key] # <--Create a value list with the former key in it.
Sets have methods that generally mimic [mathematical set operations][mathematical-sets].
176
176
Most (_not all_) of these methods have an [operator][operator] equivalent.
177
-
Methods generally take any `iterable` as an argument, while operators require that both sides of the operation are `sets` or `frozensets`.
177
+
Methods generally take any `iterable` as an argument, while operators require that both sides of the operation are `set`s or `frozenset`s.
178
178
179
179
180
180
### Membership Testing Between Sets
181
181
182
-
The `<set>.isdisjoint(<other_collection>)` method is used to test if a `sets` elements have any overlap with the elements of another.
182
+
The `<set>.isdisjoint(<other_collection>)` method is used to test if a `set`'s elements have any overlap with the elements of another.
183
183
The method will accept any `iterable` or `set` as an argument.
184
184
It will return `True` if the two sets have **no elements in common**, `False` if elements are **shared**.
185
185
@@ -275,9 +275,9 @@ True
275
275
### 'Proper' Subsets and Supersets
276
276
277
277
`<set> < <other_set>` and `<set> > <other_set>` are used to test for _proper subsets_.
278
-
A `set` is a proper subset if (`<set>` <= `<other_set>`) **AND** (`<set>` != `<other_set>`) for the `<` operator.
278
+
A `set` is a proper subset if (`<set> <= <other_set>`) **AND** (`<set> != <other_set>`) for the `<` operator.
279
279
280
-
A `set is a proper superset if `(`<set>` >= `<other_set>`) **AND** (`<set>` != `<other_set>`) for the `>` operator.
280
+
A `set` is a proper superset if (`<set> >= <other_set>`) **AND** (`<set> != <other_set>`) for the `>` operator.
281
281
These operators have no method equivalent:
282
282
283
283
```python
@@ -336,7 +336,7 @@ The operator form of this method is `<set> | <other set 1> | <other set 2> | ...
336
336
### Set Differences
337
337
338
338
`<set>.difference(*<other iterables>)` returns a new `set` with elements from the original `<set>` that are not in `<others>`.
339
-
The operator version of this method is `<set> - <other set 1> - <other set 2> - ...<other set n>`.
339
+
The operator version of this method is `<set> - <other set 1> - <other set 2> - ... - <other set n>`.
340
340
341
341
```python
342
342
>>> berries_and_veggies = {'Asparagus',
@@ -370,7 +370,7 @@ The operator version of this method is `<set> - <other set 1> - <other set 2> -
370
370
### Set Intersections
371
371
372
372
`<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]).
373
-
The operator version of this method is `<set> & <other set> & <other set 2> & ... <other set n>`
373
+
The operator version of this method is `<set> & <other set> & <other set 2> & ... & <other set n>`
0 commit comments