简体   繁体   中英

How to custom handle iteration in python dictionary?

Supposing that we have a dictinary:

links={"foo":"url1","bar":"url2","baz":"url3",}

I would like by running one for loop if it is possible like:

for link in links:
    ...
    print(next_dictinary_value)

to print the next value of dictionaly, for the last one I want to print the first. The purpose is every dictinary pair to print (connect) to another pair with out any pair conection creating a cycle(linking to each other).

I think you're asking for something like the following:

keys = links.keys()
n = len(keys)
for i in range(n):
    thisKey = keys[i]
    nextKey = keys[(i + 1) % n]
    nextValue = links[nextKey]
    print thisKey, nextValue

But be aware that a dictionary is not sorted, so you could get back the keys in any order.

links={"foo":"url1","bar":"url2","baz":"url3",}
it = iter(links)
for link in links:
    print it.next()

... baz
... foo
... bar

but try this:

it = iter(links)
it.next()
for link in links:
    try:
        print it.next()
    except StopIteration:
        it = iter(links)
        print it.next()


... foo
... bar
... baz

".... It is best to think of a dictionary as an unordered set of key:..."

You could get all the keys with keys = links.keys(). Then use them to iterate over the dictionary using the keys. Example:

>>> links={"foo":"url1","bar":"url2","baz":"url3",}
>>> k = links.keys()
>>> for i in range(0, len(k)):
...     print(links[ k[i] ])
... 
url3
url1
url2

Variable i contains the current position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM