Question

I have a program where it's supposed to get how much snow did it fall in each month of the year, store it in a dictionary and print all of the data in the correct order. I also need to print the total of snow in the whole year.

this is what I have so far:

def main():
    M=['January', 'February', 'March','April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December']
    dic = {}
    for i in range(0, len(M)):
        theKeys = list(dic.items())
        theKeys.sort()
        inpt = int(input("How much did it snow in " + str(M[i]) + " ?:"))
        dic[str(M[i])] = inpt

    theKeys = list(dic.items())
    theKeys.sort()
    print(dic)


main()

This program ask the user for the snow in the correct order. However, when it prints everything, this is what I get:

How much did it snow in January ?:1
How much did it snow in February ?:2
How much did it snow in March ?:3
How much did it snow in April ?:4
How much did it snow in May ?:5
How much did it snow in June ?:6
How much did it snow in July ?:7
How much did it snow in August ?:8
How much did it snow in September ?:9
How much did it snow in October ?:10
How much did it snow in November ?:11
How much did it snow in December ?:12

{'June': 6, 'July': 7, 'January': 1, 'December': 12, 'March': 3, 'October': 10, 'September': 9, 'May': 5, 'August': 8, 'February': 2, 'April': 4, 'November': 11}

Also, what function I can use to print the total amount of snow? sum()? My book doesn't really has a lot of information for dictionaries. Sorry if it's a really stupid question.

Was it helpful?

Solution

You have some extra lines and if you want the dictionary output to be ordered by the way it was entered you need to use an OrderedDict

>>> from collections import OrderedDict as od
>>> def myfunc():
        M=['January', 'February', 'March','April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December']
       weather = od() #defining an ordered dictionary  
       for i in range(0, len(M)):
           #theKeys = list(weather.items())  # you are not using this line
           #theKeys.sort()                   # you are not using this one
           inpt = int(input("How much did it snow in " + str(M[i]) + " ?:"))
           weather[str(M[i])] = inpt
       #theKeys = list(weather.items())      # this one is not used
       print "total snow during the year was ", sum(weather.values())

       print(weather)

the line sum(weather.values()) causes a list to be constructed with the values from the weather dictionary and then that list of values is summed

weather = od() initializes an OrderedDictionary with the name weather

>>> myfunc()
How much did it snow in January ?:1
How much did it snow in February ?:1
How much did it snow in March ?:1
How much did it snow in April ?:1
How much did it snow in May ?:1
How much did it snow in June ?:1
How much did it snow in July ?:1
How much did it snow in August ?:1
How much did it snow in September ?:1
How much did it snow in October ?:1
How much did it snow in November ?:1
How much did it snow in December ?:1
total snow during the year was  12
OrderedDict([('January', 1), ('February', 1), ('March', 1), ('April', 1), ('May', 1), ('June', 1), ('July', 1), ('August', 1), ('September', 1), ('October', 1), ('November', 1), ('December', 1)])

OTHER TIPS

When doing theKeys.sort(), you will only sort the list theKeys, not the real keys. In order to print it right, you can use OrderedDict from the module collections.

An OrderedDict is a dict that remembers the order that keys were first inserted.

Sorting will sort alphabetically thought:

for k in theKeys:
...   print k,dic[k]
... 
April 4
August 8
December 12
February 2
January 1
July 7
June 6
March 3
May 5
November 11
October 10
September 9

Regarding the sum, use dic.values()

>>> print sum(i for i in dic.values())
78

First of all, dictionaries or mapping types do not have any order respecting their keys. This is due to the hashing algorhitm in their underlying structure.

But Python comes to the rescue with its standard library. Look at the docs: http://docs.python.org/3.3/library/collections.html#collections.OrderedDict

Also you don't need to fiddle around with the keys or your month list in any way, that is done automatically using an OrderedDict.

from collections import OrderedDict

def main():
    """
    Query the amount of snow in each month of a specific year, store it and print
    the amounts. Calculates the sum of all amounts and print it.
    """

    m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
         'September', 'October', 'November', 'December']
    dic = OrderedDict()
    for month in m:
        dic[month] = int(input("How much did it snow in " + month + "? :"))

    # prints the object-representation of the OrderedDict
    print(dic)

    # a slightly better output
    from pprint import pprint
    pprint(dic)

    # calculate the sum
    print(sum(dic.values()))

if __name__ == '__main__':
    main()

Another small Tip: A good lecture for code style is http://legacy.python.org/dev/peps/pep-0008/ This does not mean, that the above code is fully compliant :)

Dictionaries are unordered. In your case that's not a problem, as you have the correct order and only a known and limited set of keys and values. Try this:

>>> print(", ".join("{}: {}".format(m, dic[m]) for m in M))
January: 1, February: 2, March: 3, April: 4, May: 5, June: 6, July: 7, August: 8, September: 9, October: 10, November: 11, December: 12

You're also doing a lot of things that you should not be doing, like sorting the keys of a dictionary when you have a non-alphabetical order that is required. You're also converting strings into strings and accessing elements by their index which is not necessary. Here's a simplified version:

>>> def snow_fall():
...     months = ['January', 'February', 'March','April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December']
...     snow_fall = {}
...     for month in months:
...         snow_fall[month] = input("How much did it snow in {}? ".format(month))
...     print(", ".join("{}: {}".format(m, snow_fall[m]) for m in months))
...     print("Total snowfall: {}".format(sum(snow_fall.values())))
... 
>>> 

Some explanation:

  1. Pythons for-loop is not like in most languages. It is more like the for-each-loop. You can iterate over a sequence of elements, and it'll provide you that element. If you absolutely need an index, you'll use enumerate. Thus the for month in months will give you January, February ..

  2. Print the correct order like I showed above

  3. Print the total snow fall by summing the values of the dict.

Demo:

>>> snow_fall()
How much did it snow in January? 10
How much did it snow in February? 5
How much did it snow in March? 18
How much did it snow in April? 3
How much did it snow in May? 0
How much did it snow in June? 0
How much did it snow in July? 0
How much did it snow in August? 0
How much did it snow in September? 20
How much did it snow in October? 30
How much did it snow in November? 80
How much did it snow in December? 120
January: 10, February: 5, March: 18, April: 3, May: 0, June: 0, July: 0, August: 0, September: 20, October: 30, November: 80, December: 120
Total snowfall: 286
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top