Dictionary within for loop does not transfer to outside for loop - Python

Viewed 1273

I am trying to make a dictionary from values in a reference .txt file, but when i make the dictionary and print it, within the for loop I get the desired result:

    ref = open("reference.txt", "r")
    contents = ref.read().splitlines()

    for line in contents:
        data = line.split(",")
        i = iter(data)
        newData = dict(zip(i, i))
        print(newData)

    Output:
    {"Bob's Diner": '001100111'}
    {"Jim's Grill": '001100111'}
    {"Tommy's Burger Shack": '01011101'}

But when I put the print statement outside the for loop, I get a different result:

    ref = open("reference.txt", "r")
    contents = ref.read().splitlines()

    for line in contents:
        data = line.split(",")
        i = iter(data)
        newData = dict(zip(i, i))

    print(newData)

    Output:
    {"Tommy's Burger Shack": '01011101'}

How can I fix this so that it compiles it into one collective, usable dictionary?

3 Answers

In your code newData is pointing to a new dictionary in each loop iteration, just create a dict outside and update it:

newData = {}
for line in contents:
    data = line.split(",")
    i = iter(data)
    newData.update(dict(zip(i, i)))

print(newData)

This is happening because you're making a new dictionary upon every iteration of the loop. Defining the dict outside the loop will solve the problem.

Just try to create a dictionary before the loop starts so the data can be stored there and be pulled out for the print statement.

ref = open("reference.txt", "r")
contents = ref.read().splitlines()

newData = {}
for line in contents:
    data = line.split(",")
    i = iter(data)
    newData = dict(zip(i, i))

print(newData)
Related