Skip to content

Commit 971aef6

Browse files
committed
feat: add how to remove items from a dictionary
1 parent 1e5eb39 commit 971aef6

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Diff for: .vscode/settings.json

+1
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@
9292
"pathobj",
9393
"pipenv",
9494
"Pipfile",
95+
"popitem",
9596
"pprint",
9697
"prereleases",
9798
"prismjs",

Diff for: docs/cheatsheet/dictionaries.md

+48
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,54 @@ Using `setdefault` we could make the same code more short:
148148
# {'name': 'Rose', 'age': 33, 'has_hair': True}
149149
```
150150

151+
## Removing Items
152+
153+
### pop()
154+
155+
`pop()` removes an item based on a given key.
156+
157+
```python
158+
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
159+
>>> wife.pop('age')
160+
# 33
161+
>>> wife
162+
# {'name': 'Rose', 'hair': 'brown'}
163+
```
164+
165+
### popitem()
166+
167+
`popitem()` remove the last item in a dictionary and returns it.
168+
169+
```python
170+
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
171+
>>> wife.popitem()
172+
# ('hair', 'brown')
173+
>>> wife
174+
# {'name': 'Rose', 'age': 33}
175+
```
176+
177+
### del()
178+
179+
`del()` removes an item based on a given key.
180+
181+
```python
182+
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
183+
>>> del wife['age']
184+
>>> wife
185+
# {'name': 'Rose', 'hair': 'brown'}
186+
```
187+
188+
### clear()
189+
190+
`clear()` removes all the items in a dictionary.
191+
192+
```python
193+
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
194+
>>> wife.clear()
195+
>>> wife
196+
# {}
197+
```
198+
151199
## Pretty Printing
152200

153201
```python

0 commit comments

Comments
 (0)