Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 339
Eman936 Avatar asked Oct 20 '25 08:10

Eman936


2 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)
like image 122
Netwave Avatar answered Oct 22 '25 04:10

Netwave


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.

like image 45
Sid Avatar answered Oct 22 '25 04:10

Sid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!