Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

loops - How to iterate over python dict from the chosen key to it again?

It is easier to explain with an example to make my question clearer:

For example:

example_dict = {1 : "A", 2 : "B", 3 : "C", 4 : "D", 5 : "E"}

Imagining that I want to start my iteration on key 3 in order to get the corresponding values ??until iterating to it again.

# Chosen the key = 3 will return:
["C","D","E","A","B"]

So what is the best way to iterate from a key to itself?

Is the iteration supposed to reach the end of the dictionary and go back to iterating from the beginning until it finds the key chosen initially?

Another example:

example_dict = {23 : "Hello", 3 : "Bye", 11 : "Shame", 45 : "Nice", 2 : "Pretty"}

# Chosen the key = 3 will return:
["Bye","Shame","Nice","Pretty","Hello"]
question from:https://stackoverflow.com/questions/66051683/how-to-iterate-over-python-dict-from-the-chosen-key-to-it-again

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use dict.values then use slicing on the list:

val_list = list(example_dict.values())
output = val_list[2:] + val_list[:2]

['C', 'D', 'E', 'A', 'B']

And to find the index of 3 turn the dict into a list and use list.index:

>>> list(example_dict).index(3)
2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...