Search code examples
pythonpython-3.xprettytable

Python PrettyTable - enter a value into column once and update count of its occurrences


I have created a pretty table as below:

from prettytable import PrettyTable
from datetime import datetime, timedelta, timezone

# objects
my_table = PrettyTable()
my_table.field_names = ["Permit_Type", "Count"]

permit_type_list = ["P1", "R4", "P1", "R2", "Q6", "Q6"]

def get_list_of_permissions():
        start_count = 0
        for permission in permit_type_list:
            start_count += 1
            my_table.add_row([permission, start_count])
        print(my_table)

get_list_of_permissions()

I want a table that gives the following output:

+--------------------------------------+-----------+
|             Permit_Type              | Count     |
+--------------------------------------+-----------+
|                 P1                   |     2     |
|                 R4                   |     1     |
|                 R2                   |     1     |
|                 Q6                   |     2     |

At the moment, my code lists the Permit_Type in the table more than once if it occurs in the list more than once and Count just increments


Solution

  • i was able to solve this myself :-)

    from collections import Counter
    from prettytable import PrettyTable
    
    # objects
    my_table = PrettyTable()
    my_table.field_names = ["Permit_Type", "Count"]
    def get_list_of_permissions():
        requests = []
        for permission in permit_type_list:
            requests_in_list.append(permission)
        req_count = Counter(requests_in_list)
    
        for key, value in req_count.most_common():
            my_table.add_row([key, value])
         print(my_table)