Issue
I am trying to create two different dictionaries with my code, then, print them separately. I've been messing with the update() function but nothing is working, here is my code.
def readTempData(filename):
with open(filename, 'r') as f:
for line in f.readlines():
day, high, low = line.split(',')
high = int(high)
low = int(low)
day = int(day)
highs = dict.update({'Day: {}, High: {}'}.format(day, high))
lows = dict.update({'Day: {}, Low: {}'}.format(day, low))
print(highs)
print(lows)
readTempData(input("Enter file name:"))
AttributeError: 'set' object has no attribute 'format'
Thank you in advance for any help!
Solution
A few different problems here. First, what is your dict named (dict
isn't instantiated anywhere that I can see)? You don't define it as far as I can see. As for update, the parameter is not a string and there's no reason to use format; the keys in the object can be strings, which is likely why you're confused, but those commas aren't wrapped in a string. I also don't see why you're using update here rather than just setting the properties values in general.
Finally, as with the other comments, I'm also not clear on what you want the dict to look like after, or why you'd separate highs and lows into separate dictionaries.
I'd probably do this:
def readTempData(filename):
with open(filename, 'r') as f:
data = {}
for line in f.readlines():
day, high, low = line.split(',')
high = int(high)
low = int(low)
day = int(day)
data[day] = {'high': high, 'low': low}
print(data)
readTempData(input("Enter file name:"))
You then can see the day as the key, with the high and low on the day easily accessible. If you want a seperate dict of high / low, you should clarify what you want as a key. You could also use a list of dictionaries which contain the day, high, and low.
For example, to access the high temperature on day 3
:
data[3]['high']
Answered By - ᴓᴓᴓ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.