Skip to content

Commit 907def2

Browse files
authored
Merge pull request #158 from kakasahebKK:kw-dictionary-changes
added dictionary subscripting
2 parents f7b2577 + 532ab3a commit 907def2

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

.vscode/settings.json

+1
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@
153153
"timedelta",
154154
"timeit",
155155
"udiskie",
156+
"Traceback",
156157
"unhashable",
157158
"useb",
158159
"vendorizing",

docs/cheatsheet/dictionaries.md

+32
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,38 @@ my_cat = {
2828
}
2929
```
3030

31+
## Set key, value using subscript operator `[]`
32+
```python
33+
>>> my_cat = {
34+
... 'size': 'fat',
35+
... 'color': 'gray',
36+
... 'disposition': 'loud',
37+
... }
38+
>>> my_cat['age_years'] = 2
39+
>>> print(my_cat)
40+
...
41+
# {'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'age_years': 2}
42+
```
43+
44+
## Get value using subscript operator `[]`
45+
46+
In case the key is not present in dictionary <a target="_blank" href="https://docs.python.org/3/library/exceptions.html#KeyError">`KeyError`</a> is raised.
47+
48+
```python
49+
>>> my_cat = {
50+
... 'size': 'fat',
51+
... 'color': 'gray',
52+
... 'disposition': 'loud',
53+
... }
54+
>>> print(my_cat['size'])
55+
...
56+
# fat
57+
>>> print(my_cat['eye_color'])
58+
# Traceback (most recent call last):
59+
# File "<stdin>", line 1, in <module>
60+
# KeyError: 'eye_color'
61+
```
62+
3163
## values()
3264

3365
The `values()` method gets the **values** of the dictionary:

0 commit comments

Comments
 (0)