Python dictionaries and working out transport carbon emissions

Some useful links

The links to the YouTube videos, and the GitHub account for this section are below:

All the information in this section has been taken from the next links:

Definition, and creating and accessing dictionary entries

Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

1. Creating a dictionary


efco2={'Bus': 0.1, 'Car': 0.2, 'Plane': 0.3, 'Ferry': 0.1, 
    'Motorbike': 0.1, 'Bicycle': 0, 'Walk': 0 }
print(efco2)
                    

2. Updating an entry


efco2['Bus'] = 0.5
print(efco2['Bus'])
print(efco2)                        
                    

3. Deleting an entry


del efco2['Bus']
print(efco2)                        
                    

4. To know with type of Python component is efco2


print(type(efco2))                      
                    

5. Creating a dictionary inside a dictionary


efco2['Bus']={'Diesel':0.10231,'CNG':0.08,'Petrol':0.10231,
    'No Fossil Fuel':0}
print(efco2)                                              
                    

6. Accessing an entry in a dictionary inside a dictionary


print(efco2['Bus']['Diesel'])                   
                    

Python dictionary methods

There are several built-in methods that can be invoked on dictionaries.

1. Method dictionary.get()

The Python dictionary.get() method provides a convenient way of getting the value of a key from a dictionary without checking ahead of time whether the key exists, and without raising an error.


print(efco2.get('Bus'))                                            
                    

2. Method dictionary.items()

Dictionary.items() returns a list of tuples containing the key-value pairs in the dictionary. The first item in each tuple is the key, and the second item is the key's value.


print(efco2.items())
print(list(efco2.items()))
print(list(efco2.items())[0][0])
print(list(efco2.items())[0][1])                                        
                    

3. Method dictionary.keys()

Dictionary.keys() returns a list of all keys in the dictionary.


print(efco2.keys())                                          
                    

4. Method dictionary.values()

Dictionary.values() returns a list of all values in the dictionary.


print(efco2.values())                                        
                    

Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

1. Looping example 1


for k, v in efco2.items():
    print(k, v) 
                    

2. Looping example 2


for k1, v1 in efco2.items():
    for k2, v2 in efco2[k1].items():
        print(k1, v1)
        print(k2, v2)
                    

Using dictionaries inside our app, and working out transport carbon emissions

In this section, we work out users' transport carbon emissions. In the carbon_app.html file, the users select the type of transport. Then, the user is redirected to the webpage where the user introduces the number of kilometers and the type of fuel (e.g., new_entry_bus.html file, new_entry_car.html file, etcetera). In that webpage, the users introduce the kilometers and the type of fuel by using the form that we have created in the package carbon_app, in the forms.py file. Once that the user has introduced the kilometers and the type of fuel, the carbon emissions are calculated in the routes.py file inside the carbon_app package, and the user is redirected to the your_data.html file.

In this section, we focus on the mathematical model to work out the transport carbon emissions. In the next section, we focus on the query that we make to the database to disclose the carbon emissions in the your_data.html file.

In the package carbon_app, in the routes.py file, we focus on the route new_entry_bus (the procedure for the other means of conveyance is the same).

  1. We need to import the form that we created in the package carbon_app, in the file forms.py.
    
    from capp.carbon_app.forms import BusForm
                                
  2. We define the emission factor matrixes.
    
    efco2={'Bus':{'Diesel':0.10231,'CNG':0.08,
        'Petrol':0.10231,'No Fossil Fuel':0},
        'Car':{'Petrol':0.18592,'Diesel':0.16453,
        'No Fossil Fuel':0},...}
    efch4={'Bus':{'Diesel':2e-5,'CNG':2.5e-3,
        'Petrol':2e-5,'No Fossil Fuel':0},
        'Car':{'Petrol':3.1e-4,'Diesel':3e-6,
        'No Fossil Fuel':0},...}                            
                                
  3. We define the form that will be used in the new_entry_bus.html file.
    
    @carbon_app.route('/carbon_app/new_entry_bus', 
        methods=['GET','POST'])
    @login_required
    def new_entry_bus():
        form = BusForm()
        return render_template('carbon_app/new_entry_bus.html',
        title='new entry bus', form=form)
                                

Package carbon_app, routes.py file

@carbon_app.route('/carbon_app/new_entry_bus',
    methods=['GET','POST'])
@login_required
def new_entry_bus():
    form = BusForm()
    if form.validate_on_submit():
        kms = form.kms.data
        fuel = form.fuel_type.data
        transport = 'Bus'
        # kms = request.form['kms']
        # fuel = request.form['fuel_type']

        co2 = float(kms) * efco2[transport][fuel]
        ch4 = float(kms) * efch4[transport][fuel]
        total = co2+ch4

        co2 = float("{:.2f}".format(co2))
        ch4 = float("{:.2f}".format(ch4))
        total = float("{:.2f}".format(total))

        emissions = Transport(kms=kms, transport=transport,
            fuel=fuel, co2=co2, ch4=ch4, total=total, author=current_user)
        db.session.add(emissions)
        db.session.commit()
        return redirect(url_for('carbon_app.your_data'))
    return render_template('carbon_app/new_entry_bus.html', 
        title='new entry bus', form=form)

  1. Once that the user introduces the kilometers and the type of fuel, we work out the transport carbon emissions. We proceed in four steps:
    1. We take the data from the form.
      
      kms = form.kms.data
      fuel = form.fuel_type.data
      transport = 'Bus'                                    
                                      
    2. We work out the emissions.
      
      co2 = float(kms) * efco2[transport][fuel]
      ch4 = float(kms) * efch4[transport][fuel]
      total = co2+ch4                                    
                                      
    3. We round the data to avoid having a lot of decimals.
      
      co2 = float("{:.2f}".format(co2))
      ch4 = float("{:.2f}".format(ch4))
      total = float("{:.2f}".format(total))                                    
                                      
    4. We store the data in the database.
      
      emissions = Transport(kms=kms, transport=transport, 
      fuel=fuel, co2=co2, ch4=ch4, total=total, 
      author=current_user)
      db.session.add(emissions)
      db.session.commit()
                                      

Queries and tables

In this section we make a query to the database to collect information about the transport, the fuel, the kilometers, and the emissions. After making a query, we disclose the information by using a Bootstrap table. We also learn to delete an entry from our database.

Some useful links

The links to the YouTube video, and the GitHub account for this section are below:

Query

We make a query from the database by introducing the next filters:

  1. We filter by the author.

  2. We filter the entries for the last five days.

  3. We order the data in descending order according to the date.

  4. We order the data in ascending order according to the transport.

carbon_app package, routes.py file

entries = Transport.query.filter_by(author=current_user). \
filter(Transport.date> (datetime.now() - timedelta(days=5))).\
order_by(Transport.date.desc()).order_by(Transport.transport.asc()).all()

Table

By using a bootstrap table, we disclose the data that we obtained in our query. The link to the bootstrap tables can be found below:

We must introduce the next changes in the your_data.html file.


<table class="table">
<thead class="thead-dark">
    <tr>
        <th scope="col">User</th>
        <th scope="col">Date</th>
        <th scope="col">Kilometres</th>
        <th scope="col">...</th>
        <th scope="col">Delete</th>
    </tr>
</thead>
<tbody>
    {% for entry in entries %}
        <tr>
            <th scope="row">{{ current_user.username }}</th>
            <td>{{ entry.date.strftime("%m-%d-%Y") }}</td>
            <td>{{ entry.kms }}</td>
            <td>{{ ...}}</td>
            <td><a href="{{ url_for('carbon_app.delete_emission', 
            entry_id = entry.id) }}" 
            class="btn btn-outline-danger btn-sm">Delete</a></td>
        </tr>
    {% endfor %}
</tbody>
</table>                  
                

Delete an entry in the database

We could be interested in allowing the user to erase an entry from the database. To do that, we need to introduce a link in the table, and a new route to delete the entry. The link in the table is in the code above. I also disclose that code in the next lines of code:

We must introduce the next changes in the your_data.html file.


<td><a href="{{ url_for('carbon_app.delete_emission', 
entry_id = entry.id) }}" 
class="btn btn-outline-danger btn-sm">Delete</a>
</td>           
                

In the carbon_app package, in the routes.py file, we need to introduce a new route to delete an entry from the database. We proceed in four steps:

  1. We make a query in the database to find the entry. If the entry is not in the database, we provide a 404 message.

  2. By using the delete method, we delete the entry.

  3. By using the commit method, we commit the changes.

  4. We disclose a message and redirect the user to the your_data.html file.

carbon_app package, routes.py file

@carbon_app.route('/carbon_app/delete-emission/<int:entry_id>')
def delete_emission(entry_id):
    entry = Transport.query.get_or_404(int(entry_id))
    db.session.delete(entry)
    db.session.commit()
    flash("Entry deleted", "success")
    return redirect(url_for('carbon_app.your_data'))

Weekly challenge

In this chapter, we focus on the carbon emissions generated by the buses. In the weekly challenge, we must introduce the forms, the routes, and the html files for the rest of means of conveyance.