Home > Mobile >  Python getting my program to output one variable once in a loop
Python getting my program to output one variable once in a loop

Time:12-21

I have no idea how to explain this but my task is to export a dict into a txt file with it being formatted right. The dict looks like this:

obstacles = {4: [(5, 6), (9, 11)],
              5: [(9, 11), (19, 20), (30, 34)],
              13: [(5, 8), (9, 11), (17, 19), (22, 25), (90, 100)]}

and it is supposed to output as(the correct way):

004:   5-6      9-11
005:   9-11    19-20    30-34
013:   5-8      9-11    17-19    22-25    90-100

Now I created a code and it outputs it to a text file like this:

004:    5-6
004:    9-11
005:    9-11
005:    19-20
005:    30-34
013:    5-8
013:    9-11
013:    17-19
013:    22-25
013:    90-100

This is how my code looks like, I mean it outputs like this because it is in a for loop but if anyone can help me understand and help me fix up my code it would be much appreciated. This is how my code looks like:

with open('filename.txt', 'w') as f:
    for v, k in obstacles.items():
        tridec = f'{v:03}'
        for broj1, broj2 in k:
            xx = str(broj1)   "-"   str(broj2)
            f.write("%s:\t" % tridec   "%s\n" % xx)

I tried using the .join function like this:


with open('filename.txt', 'w') as f:
    for v, k in obstacles.items():
        tridec = f'{v:03}'
        r = ("-".join(str(z) for z, m in k))
        r1 = ("-".join(str(m) for z, m in k))
        mr = r   "\t"   r1
        f.write("%s:\t" % tridec   "%s\t" % r   "%s\n" % r1)

But this outputs the thing like this:

004: 5-9 6-11
005: 9-19-30 11-20-34
013: 9-17-22-90 11-10-25-100

I know the reason why it outputs it like this, because it is combining the z first and adding a "-" and then the m variable. But it should be like this example 004: z - m z - m. The code looked approx like this and I wrote this from my head when I tried to rewrite it because I deleted this method of getting the numbers into the txt file.

CodePudding user response:

Loop over the value (which is a list of tuples) for each key and call f.write for each element.

with open('filename.txt', 'w') as f:
    for v, k in obstacles.items():
        tridec = f'{v:03}:'
        f.write(tridec)
        for a,b in k:
            f.write(f'\t{a}-{b}')
        f.write('\n')
  • Related