Skip to content

Commit 52048d3

Browse files
committed
Update dictionary |= operator
1 parent f3392f3 commit 52048d3

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5811,6 +5811,38 @@ In case of common keys between the two operands (dictionaries), the values of th
58115811

58125812
In the above example, both `d` and `n` shared a common key `yr`. The value corresponding to `yr` in `n` gets priority.
58135813

5814+
The `|=` (union) augmented assignment operator can be used to update the dictionary with keys and values from another dictionary or an iterable of (key, value) pairs.
5815+
5816+
``` python
5817+
>>> d = {"book": "Python", "year": 1990}
5818+
>>> dnew = {"author": "Guido"}
5819+
>>> d |= dnew
5820+
>>> d
5821+
{'book': 'Python', 'year': 1990, 'author': 'Guido'}
5822+
```
5823+
5824+
If both the dictionaries share a common key, then the value corresponding to the key in the right operand is the updated value.
5825+
5826+
``` python
5827+
>>> d = {"book": "Python", "year": 1990}
5828+
>>> dnew = {"author": "Guido", "year": 2000}
5829+
>>> d |= dnew
5830+
>>> d
5831+
{'book': 'Python', 'year': 2000, 'author': 'Guido'}
5832+
```
5833+
5834+
In the above example, both `d` and `dnew` shared a common key `year`. The value (`1990`) corresponding to `year` in `d` is updated with the new value.
5835+
5836+
The `|=` operator also works in case the right operand is an iterable instead of a dictionary as shown in the example below.
5837+
5838+
``` python
5839+
>>> d = {"book": "Python", "year": 1990}
5840+
>>> inew = [("author", "Guido"), ("year", 2000)]
5841+
>>> d |= inew
5842+
>>> d
5843+
{'book': 'Python', 'year': 2000, 'author': 'Guido'}
5844+
```
5845+
58145846
## Traversing a Dictionary
58155847

58165848
Compared to position based indexing of `list` or `tuple`, dictionaries are indexed based on the key.

0 commit comments

Comments
 (0)