|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stay one step ahead of the competition. Evaluate and give feedback
on some of the hottest web development tools on the market today.
Make your opinion heard! Click
Here
|
|
#1
|
|||
|
|||
|
using iterator on a dictionary
how do you iteratre through a dictionaries keys? i see that a dictionary has iterkeys() that returns an iterator over the ekys, but i have no idea how to use the iterator object and documentation on the web stinks
|
|
#2
|
||||
|
||||
|
There are actually a few ways you can iterate over a dictionary, so you dont have to use an iterator anyway.. but heres a few working examples anyway!
Code:
dictionary = {'1': 'one', '2': 'two', '3': 'there'}
for key in dictionary.iterkeys():
print key, dictionary[key]
Code:
dictionary = {'1': 'one', '2': 'two', '3': 'there'}
for key in dictionary.keys():
print key, dictionary[key]
Code:
dictionary = {'1': 'one', '2': 'two', '3': 'there'}
for key, value in dictionary.items():
print key, value
Mark. |
|
#3
|
||||
|
||||
|
Here's another...
In python 2.2,2.3 you can iterate directly over dictionaries because they contain an iterator object. The dictionary iterator will return the next key in the un-ordered list of keys. So you can do this Code:
a = {"tom":2.3,"****":21.1,"harry":1.1}
for key in a:
print key, a[key]
where in calls the next method of the iterator. I just noticed you can't use *Richard* in an example! |
|
#4
|
|||
|
|||
|
There's also the dict.items(), which returns a tuple containing the key and the value.
Code:
>>> for (key, item) in {1:2,2:3,3:4}.items():
... print key, item
...
1 2
2 3
3 4
>>>
I know you asked for the keys, but it's useful sometimes to get the item straight-away. |
|
#5
|
||||
|
||||
|
i kinda already gave an example of this one Perc
![]() |
|
#6
|
|||
|
|||
|
Hmm. Didn't see that example earlier. You sure you didn't add it after?
![]() |
|
#7
|
||||
|
||||
|
The advantages of being mod boy
.. Naw, to my regret i cant get around that anoying last edited line ![]() Mark. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > using iterator on a dictionary |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|