Assume I have a file of the following format:
a,1
b,2
c,3
d,4
Here is my code:

def junk(f):
    d1 = {}
    d2 = {}
    for line in f:
        columns = line.split(",")
        letters = columns[0]
        numbers = columns[1]
        d1[letters] = numbers
        d2[numbers] = letters
    return (d1, d2)
    
def something():  
    print d1
    print d2
    
if __name__ == "__main__":
    f = open("filename.txt")
    d1 = junk(f)[0]
    d2 = junk(f)[1]

Assume I want to call function something. It cannot print d1 and d2 unless I add them to the main block. As soon as I add d1 and d2 to the "main" block and call either of the two functions, both return two empty dictionaries. Why does this happen? How can I fix it? Please help! I've been trying to figure it out the whole day!

Dani AI

Generated

The symptom (empty dicts) comes from reading the same file handle more than once: the first read consumes the file (the iterator goes to EOF), so a second call sees no lines and returns empty mappings. was on the right track asking whether the loader actually returns data; the usual bug is not the parser itself but how it's called. correctly noted the issue was solved elsewhere.

Fixes (choose one)

  • Call the parser once and unpack both dictionaries: do not invoke the reader twice on the same file object.
  • Rewind the file before a second read with f.seek(0).
  • Prefer reopening the file or (better) returning both dicts and passing them to other functions instead of relying on globals.

Example of a robust pattern:

def parse_file(fh):
    a_to_b = {}
    b_to_a = {}
    for raw in fh:
        line = raw.strip()
        if not line:
            continue
        key, val = line.split(',', 1)
        key = key.strip()
        val = val.strip()
        try:
            val = int(val)
        except ValueError:
            pass
        a_to_b[key] = val
        b_to_a[val] = key
    return a_to_b, b_to_a

with open('filename.txt') as fh:
    a_to_b, b_to_a = parse_file(fh)

def something(a_map, b_map):
    print(a_map)
    print(b_map)

something(a_to_b, b_to_a)

Extra tips

  • Use split(',', 1) to avoid breaking values that contain commas.
  • Always strip() lines to remove newlines and whitespace.
  • Avoid globals: pass the dicts into functions so the flow is explicit.
  • If you really must call the parser twice, call fh.seek(0) between calls or reopen the file.

Recommended Answers

All 3 Replies

What is the load_airports function? Are you sure that it is returning something into your dictionaries?

What is the load_airports function? Are you sure that it is returning something into your dictionaries?

Sorry, copied a part of the other program. I fixed it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.