Get the next element of an array

User

I have such an array:

{"1":"https:\/\/proxy1...","2":"https:\/\/proxy2...","3":"https:\/\/proxy2...","7":"https:\/\/proxy2...", "10":"https:\/\/proxy2..."}

Еhere is a variable that contains the element id. For example: randElem = 3

I need to get the next element of an array. If the element ids are consecutively 1,2,3,4,5, there is no problem. Was it like this:

randElem = 3
data = json.load(open('proxies.json'))
count = len(data)

if randElem > count:
    print(data[str(1)])
elif randElem == count:
    print(data[str(randElem)])
else:
    randElem = randElem+1
    print(data[str(randElem)])

But, if the array is like above, it doesn't work. And also if randElem = the last element in the array. Need to get the first element

How can I do it?

Unmitigated

You can first create a sorted list of the keys from the dict and use that to find the next key.

ids = sorted(map(int, data))
randElem = min(randElem, ids[-1])
idx = ids.index(randElem) # assuming the key exists
print(data[str(ids[(idx + 1) % len(ids)])])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related