Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to add data to different dictionaries and print one then another

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading