Dictionaries, popitem() method example

Tim Gahnström /Bladerman tim at bladerman.com
Thu Nov 1 07:59:20 EST 2001


"Antonios B. Kaklis" <antoni3 at otenet.gr> skrev i meddelandet

> In the Python Library Reference, Section 2.1.6 "Mapping Types"
> It says: "a.popitem( )" --->Note 6: Is useful to destructively iterate
over
>                                                      a dictionary as often
> used in set algorithms!
>
> I don't understand

1) what is "Destructively iteration over a dictionary"
This means that popitem() will return an item from the dictionarry and also
remove it from the dictionarry.
eg.

>>> a={1:"a", 3:"b", 5:"c"}
>>> a
{5: 'c', 3: 'b', 1: 'a'}
>>> a.popitem()
(5, 'c')
>>> a
{3: 'b', 1: 'a'}

first we creat a dictionary called a
Then we look what is in it
Then we pop out one item,
Then we look what is left in a
wich is the dictionarry - what we popped out.

usually you use it to loop (=itterate) over all elements in a dictionarry.

eg.
>>> def loop(dict):
...  print dict.popitem()
...  loop (dict)
...
>>> loop(a)
(5, 'c')
(3, 'b')
(1, 'a')

Here comes an errormessage because we have printed all elements in the
dictionarry and now it is empty so we canot pop anymore.


> 2) Set Algotithms
A set is a colection of items, usually representet in Python by Dictionarys.
Algorithms involving Dictionarrys can therby be called Set algorithms.

Gl
Tim





More information about the Python-list mailing list