Python Forum
Pollution level using dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pollution level using dictionaries
#31
Did you run wavic code without a problem? (I got an error with his code)
The for loop you created is inside the else statement. So, every time a new city is added it will calculate the average pollution.
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#32
If I understood wavic correctly this is what he suggested:

def average(januar):
    k = {}
    for day, data in januar.items():
        for city, pollution in data.items():
            if k[city]:
                k[city].append(pollution)
            else:
                k[city]=[]
                k[city].append(pollution)
And then I wrote to my teacher already yesterday and he hasn't replied until not long ago and he said that to here, it is correct and suggested to continue with something like this:

for key in k:
    k[key] = sum(k[key])/len(k[key])
return k
key should be pollution in this case, shouldn't be?

But when I run what I posted in the previous post I get KeyError #confused
Reply
#33
"key should be pollution in this case, shouldn't be?"
No, the elements in a dictionary are dict = {keys: values}. So, if you call dict[key] it will return the values which in your case the pollution. (ref:https://www.tutorialspoint.com/python/python_dictionary.htm)

Also,

for key in k:
    k[key] = sum(k[key])/len(k[key])
return k
this need to be inside the first indent.

Output:
{'Texas': 71.0, 'Moscow': 63.666666666666664, 'Berlin': 54.333333333333336, 'Athens': 45.0}
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#34
I think i understand what you first wrote! So I should call the city (k[city]?) in order to get the pollution value instead of what I did when I wrote k[pollution]?

And, what do you mean by "this needs to be inside the first indent?" I'm sorry but my English might not be as good or should I say Python language? :)
Reply
#35
"... what do you mean by "this needs to be inside the first indent?" ..."
Indentation is leading whitespace which Python is used to determine the grouping of statements.

So I should call the city (k[city]?) in order to get the pollution value instead of what I did when I wrote k[pollution]?
Not unless you planning to look at the average over time.

def povprecje(januar):
    k = {}
    for day, data in januar.items():
        for city, pollution in data.items():

            try:
                k[city].append(pollution)
            except:
                k[city]=[]
                k[city].append(pollution)

    for key in k:
        k[key] = sum(k[key])/len(k[key])

    return k

januar = {
1: {'Texas': 126, 'Moscow': 64, 'Berlin': 57, 'Athens': 35,},
2: {'Texas': 53, 'Moscow': 56, 'Berlin': 58,},
3: {'Texas': 34, 'Moscow': 71, 'Berlin': 48, 'Athens': 55,}
}
  
print(povprecje(januar))

Don't worry about my try and exception it a work around to "if k[city]:" for the Python IDLE.
When my code doesn't work I don't know why **think** and when my code works I don't know why **think**
Reply
#36
Hello again!
I suggest you go back and learn what is a dictionary, what is a dictionary key and what is dictionary value and how to loop over a dictionary.
Your English is not the issue. I understand you pretty well. Mine is not as good as I want too.

Let's say that you have a dog. And let call it Jerry. And you want to store some information about this dog. The dictionary is the first data type which probably you will choose. You have a key which you will use to find the data.

key       data
  |            |
{'dog': "Jerry"}

When you want to get the name of the dog you are using the key to get it.

my_dog = {'dog': "Jerry"} # here we define a dictionary 'my_dog'

my_dog_name = my_dog["dog"] # now we use the key ( 'dog' ) to get the name ( "Jerry" ) and put it into my_dog_name.
But what if we want to keep more data and not just the name? For example the breed, the age, and the last vaccination date. Along with the name, these are four values. We are using a list to pack them. Why list? Because it is mutable and we can add something else.

my_dog = {'dog': ["Jerry", "Cocker Spaniel", 3, '17.05.2016']}
Now we have the name, the breed, the age and the last vaccination date. Again we get the data using the key ( 'dog' ):

my_dog_data = my_dog['dog']
my_dog_data now holds the whole list we have provided as a value: ["Jerry", "Cocker Spaniel", 3, '17.05.2016']

Since my_dog['dog'] returns a list we can get the breed for example just pointing to its index:

my_dog_breed = my_dog['dog'][1]
And we get "Coker Spaniel" inside the my_dog_breed variable.

But what if we want to process each value separately? We have to loop over the data:

for value in my_dog['dog']: # my_dog['dog'] will return the whole list and 'value' will holds one element from it on each iteration
    print(value)
   And we get:
Output:
Jerry Cocker Spaniel 3 17.05.2016
What if you want to keep and your friend's dogs data? 

our_dogs = {
                   "me": ["Jerry", "Cocker Spaniel", 3, '17.05.2016'],
                    "Marta": ["Pincky", "Poodle", 1, '29.10.2017'],
                    "Tom": ["King", "Dogo Argentino", '5.12.2016']
                  }
Now if we loop over the 'our_dogs':
for dog in our_dogs:
    print(dog)
We get only the keys:
Output:
Tom me Marta
It's not what we want. If we want to print the name ( the key ) along with the data we do it like this:
for name, data in our_dog.items(): # the items() method returns a tuple (key, value) so 'name' will hold the key and 'data' - the value | name, data = (key, value)
    print(name, data)
But we don't want to get a list. We want each data value separate. Well, we have to start another loop over the data in order to do it. One loop into another.
for name, data in our_dogs.items():
    print(name) # we have a person's name and in the inner loop we are going to use 'data' to loop over it

    for value in data: # data is a list now, an iterable
        print("    ", value) # we put some spaces before the value to have a pretty print
The output:
Output:
Tom      King      Dogo Argentino      5.12.2016 me      Jerry      Cocker Spaniel      3      17.05.2016 Marta      Pincky      Poodle      1      29.10.2017
This is how we operate with dictionaries. We can have a list of dictionaries within another dictionary or list or a tuple. You can create a pretty complicated data structure.

Knowing this, how we can calculate the average? We have the same structure of data. A dictionary and for each key, we have a list of integers. But it's easier because this time we don't have to loop through the list. And do not use a single character variable name since it doesn't tell us what it is inside.
print("Averages:")
for city, pol_values in pol_sumarize: # instead of 'k' I called it 'pol_summarize'

    summarize = sum(pol_values) # sum will summarize all the 'pol_values' integers. 
    num_days = len(pol_values)
    average = summarize / num_days # it's just that
    
    print("    ", city, average) # again some space at the  beginning to prettify the print
The output:
Output:
Averages:      Berlin 54.333333333333336      Moscow 63.666666666666664      Athens 45.0      Texas 71.0
Now, this is a pretty much complete solution. All you have to do is to return the averages instead of printing them. Probably another dict which will look like this:
{city: average, another_city: average, etc}

I don't like to provide complete solutions in Homework forum but you are about the same every time. I rather prefer to show you how all this works and make an exception. After all this forum is for teaching Python. There are professionals here. I am not.

And have fun. It's easier.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#37
Dear wavic, thank you for taking that much time and having so much patience with me.

I'll admit that the task looks much more intimidating than it really is at the end.

I don't like being handed solutions either because that doesn't add anything to my knowledge and at the end it is me who has to pass the exams.

And with this extended explanation you gave I understand things a lot better. So thank you so much, again! I found some new motivation for programming :)

So, after all the help you gave me, I want to share my final program with you, which is just slightly different from your last suggestion.

Reply
#38
Good!
A final word. If you put empty lines at some places it will improve the readability of the code. Some doc strings also.
A question. Why are you keep checking for pollution >=50 when you said:
Quote:I have to define a function that returns for each city the number of days when pollution was above 50.

def number_of_polluted_days(januar):
    """Counting the days with pollution > 50"""

    k = {}
    for day, data in januar.items():
        for city, pollution in data.items():

            if city not in k:
                k[city]=0

            if pollution >=50:
                k[city] += 1

    return k
 
def average(januar):
    """Calculate the average pollution"""

    k = {}
    for day, data in januar.items():
        for city, pollution in data.items():

            if city in k:
                k[city].append(pollution)
            else:
                k[city]=
                k[city].append(pollution)

    for city in k:
        k[city] = sum(k[city])/len(k[city])

    return k
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Monthly pollution rate RbaPhoenix 4 2,688 Mar-28-2020, 04:01 PM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020