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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With