Home > Software design >  How to make a loop stop after it's done iterating through a key's values?
How to make a loop stop after it's done iterating through a key's values?

Time:02-06

Title is a bit complex, and I'm fairly new to Python.

Here's what my problem is, I currently have a dictionary, and I'm trying to create a tuple according a rule. I have got the tuple creation under control, I just need a way to iterate differenly so that I can create my tuple

Here's what I have:
The list that "i" goes through is titled DEMANDPOINT= [1,2,3.......954]

The second list I have is, a tuple that consists of 734 groups each has 5 numbers, titled tuples of stations "j" goes through this

I have a nested dictionary that goes like this: distance5 = {1: {513: 0.6291397367847646, 279: 0.7823399663201693, 582: 0.8703625254182541, 392: 1.0191414569956174, 297: 1.0660162833624383}, 2: {297: 1.1155101452481397, 279: 1.458507500394341, 513: 1.7296683927743512, 582: 1.8516961940275365, 392: 2.0394772611422898}

I want "iterator i =1 " to stop after it checks tuple_of_stations's first group of 5 numbers, and switch to 2.

Here's the code that I'm using to create my tuple.

for i in DEMANDPOINT:
    for j in tuple_of_stations:
        if distance5[i][j] <= Dc:
            N[i]  = (j,)
    if len(N[i]) == 0:    
        N[i]  = ((min(distance5[i], key=distance5[i].get)),)

I want the "iterator i" to stop after it has checked the values of 1st dictionary. I have no idea how I can do that.

Basically like this: example image In the example, I have explained how I want the iterators to go through.

Sorry if that's not a clear explanation, I tried to explain my problem as much as I could. Thanks in advance

CodePudding user response:

I have changed a little the code, let me know if now it does what you need:

N = {}
for i in distance5:
    tuple_of_stations = list(distance5[i].keys())
    c = 0
    for j in tuple_of_stations:
        if distance5[i][j] <= Dc:
            if i not in N:
                N[i] = (j,)
            else:
                N[i]  = (j,)
            c  = 1
            if c >= 5:
                break
    if i not in N:
        N[i] = ((min(distance5[i], key=distance5[i].get)),)
    elif not N[i]:
        N[i]  = ((min(distance5[i], key=distance5[i].get)),)
  •  Tags:  
  • Related