Skip to content

Commit a5aaab9

Browse files
authored
Merge pull request #68 from UoMResearchIT/53-add-items-method-to-spintting-out-keys-and-values
feat: example added for .items() function
2 parents 014b568 + 7e70a87 commit a5aaab9

1 file changed

Lines changed: 26 additions & 2 deletions

File tree

episodes/02-dictionaries.md

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,15 +293,15 @@ d.keys()
293293
```
294294

295295
```output
296-
dict_keys(['alice', 'bob', 'jane', 'tom', 'david'])
296+
dict_keys(['alice', 'bob', 'jane'])
297297
```
298298

299299
```python
300300
d.values()
301301
```
302302

303303
```output
304-
dict_values([12, 18, 24, 54, 87])
304+
dict_values([12, 18, 24])
305305
```
306306

307307
Note that the *dict\_keys* and *dict\_values* objects are iterable but are not lists. This means that they can be used somewhere like a `for` loop but you can not index them directly.
@@ -326,6 +326,30 @@ list(d.values())[0]
326326
12
327327
```
328328

329+
It is also possible to iterate through the keys and items in the dictionary at the same time using the `items` function,
330+
which returns a *dict\_items* object containing `key, value` pairs:
331+
332+
```python
333+
d.items()
334+
```
335+
336+
```output
337+
dict_items([('alice', 35), ('bob', 18), ('jane', 24)])
338+
```
339+
340+
This is very useful when using a dictionary in a `for` loop:
341+
342+
```python
343+
for key, value in d.items():
344+
print("Name:", key, " Age:", value)
345+
```
346+
347+
```output
348+
Name: alice Age: 35
349+
Name: bob Age: 18
350+
Name: jane Age: 24
351+
```
352+
329353
## Presence (or not) of an element inside a dictionary
330354

331355
It is possible to test if a key is present in the dictionary (or not) using the keyword `in`, just as we did at the start of this lesson for values within a list:

0 commit comments

Comments
 (0)