Skip to content

Commit 03b8132

Browse files
committed
Looping over a dictionary
1 parent 4d9e34c commit 03b8132

File tree

1 file changed

+39
-19
lines changed

1 file changed

+39
-19
lines changed

docs/datastructure.rst

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -347,25 +347,6 @@ You must remember that no mutable object can be a *key*, that means you can not
347347
>>> dict((('Indian','Delhi'),('Bangladesh','Dhaka')))
348348
{'Indian': 'Delhi', 'Bangladesh': 'Dhaka'}
349349

350-
.. index:: items
351-
352-
If you want to loop through a dict use *items()* method.
353-
354-
::
355-
356-
>>> data
357-
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
358-
>>> for x, y in data.items():
359-
... print("%s uses %s" % (x, y))
360-
...
361-
Kushal uses Fedora
362-
Jace uses Mac
363-
kart_ uses Debian
364-
parthan uses Ubuntu
365-
366-
For Python 3.7 dictionaries maintain the insertion order of the items. While looping over *items()* method,
367-
you will get the key/value combination based on the insertion order of those items.
368-
369350
Many times it happens that we want to add more data to a value in a dictionary and if the key does not exists then we add some default value. You can do this efficiently using *dict.setdefault(key, default)*.
370351
::
371352

@@ -391,6 +372,45 @@ When we try to get value for a key which does not exists we get *KeyError*. We c
391372
>>> data.get('foo', 0)
392373
0
393374

375+
376+
Looping over a dictionary
377+
--------------------------
378+
379+
If you just do a `for` loop over a dictionary, it will provide you all the available keys in the dictionary.
380+
381+
::
382+
383+
>>> data
384+
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
385+
>>> for x in data:
386+
... print(f"Key = {x}")
387+
...
388+
Kushal
389+
Jace
390+
kart_
391+
parthan
392+
393+
394+
.. index:: items
395+
396+
If you want to loop through a dict use *items()* method.
397+
398+
::
399+
400+
>>> data
401+
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
402+
>>> for x, y in data.items():
403+
... print("%s uses %s" % (x, y))
404+
...
405+
Kushal uses Fedora
406+
Jace uses Mac
407+
kart_ uses Debian
408+
parthan uses Ubuntu
409+
410+
From Python 3.7 dictionaries maintain the insertion order of the items. While
411+
looping over *items()* method, you will get the key/value combination based on
412+
the insertion order of those items.
413+
394414
.. index:: enumerate
395415

396416
If you want to loop through a list (or any sequence) and get iteration number at the same time you have to use *enumerate()*.

0 commit comments

Comments
 (0)