Python Forum
making variables in my columns and rows in python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: making variables in my columns and rows in python (/thread-35414.html)



making variables in my columns and rows in python - kronhamilton - Oct-31-2021

I've been searching the internet for the answer to my problem, but to no avail. I'm trying to put data into rows and columns, but I have variables and I thought that I had found the answer to my problem, but it wasn't a solution to the variable part of it. Is there a way that I could modify this method a little bit to include variables or is there another way to do this?

#inputs
name = input("Who are you? ")
supermarket = input("Where are you going? ")
date = input("What day is it? ")
item = input("What are you buying? ")
price = float(input("How much is the item you are buying? "))
quantity = float(input("How many are you buying? "))
vehicle = input("How do you plan to get there? ")
commute_cost = float(input("How much does that cost one way? "))

#process
total = price * quantity
total_commute_cost = commute_cost * 2
trip_total = total + total_commute_cost

#data for column
data = '''\
Item Price Quantity Total
item price quantity total'''

#making the table into columns and rows
rows = [ line.strip().split(' ') for line in data.split('\n') ]
cols = zip(*rows)
col_widths = [ max(len(value) for value in col) for col in cols ]
format = ' '.join(['%%%ds' % width for width in col_widths ])

#output
print("     ")
print("Shopper name:", name)
print("     ")
print(supermarket)
print(date)
print("     ")
for row in rows:
    print (format % tuple(row))
with an output of
Output:
Item Price Quantity Total item price quantity total
but I want an output, if the variables have been answered by the user,

Output:
Item Price Quantity Total Milk 4 2 8
im having a real hard time trying to find anything about it.
thanks ahead of time.


RE: making variables in my columns and rows in python - Larz60+ - Oct-31-2021

you could use pandas:

code:
from CreateDict import CreateDict
import pandas as pd


class MyApp:
    def __init__(self):
        self.cd = CreateDict()
    
        self.data = {}

    def dispatch(self):
        self.get_data()
    
    def add_row(self):
        name = input("Who are you? ")
        if name.strip() == 'quit':
            return 'quit'
        dnode = self.cd.add_node(self.data, name)
        supermarket = input("Where are you going? ")
        self.cd.add_cell(dnode, 'destination', supermarket)
        date = input("What day is it? ")
        self.cd.add_cell(dnode, 'date', date)
        item = input("What are you buying? ")
        self.cd.add_cell(dnode, 'item', item)
        price = float(input("How much is the item you are buying? "))
        self.cd.add_cell(dnode, 'price', price)
        quantity = float(input("How many are you buying? "))
        self.cd.add_cell(dnode, 'Quantity', quantity)
        vehicle = input("How do you plan to get there? ")
        self.cd.add_cell(dnode, 'vehicle', vehicle)
        commute_cost = float(input("How much does that cost one way? "))
        self.cd.add_cell(dnode, 'commute_codt', commute_cost)
        
        return 'ready'
    
    def get_data(self):
        retval = None
        print("add data for each user, type 'quit' when done")
        while retval != 'quit':
            retval = self.add_row()
        self.cd.display_dict(self.data)
        print()
        df = pd.DataFrame.from_dict(self.data)
        print(df)


def main():
    ma = MyApp()
    ma.dispatch()


if __name__ == '__main__':
    main()
You will need this module (same directory as main script) please use script name shown
CreateDict.py
import os
 
class CreateDict:
    """
    Generic Software tools used by Trailmapper.
 
    CreateDict.py - Contains methods to simplify node and cell creation within
                    a dictionary
 
    Usage: 
     
        The best way to learn what can be done is to examine the testit function
        included in this module.
 
        new_dict(dictname) - Creates a new dictionary instance with the name
            contained in dictname
 
        add_node(parent, nodename) - Creates a new node (nested dictionary)
            named in nodename, in parent dictionary.
 
        add_cell(nodename, cellname, value) - Creates a leaf node within node
            named in nodename, with a cell name of cellname, and value of value.
 
        display_dict(dictname) - Recursively displays a nested dictionary.
 
    Requirements:
 
        Trailmapper software:
            None
 
        Python standard library:
            os
     
    Author: Larz60+  -- May 2019.
    """
    def __init__(self):
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
 
    def new_dict(self, dictname):
        setattr(self, dictname, {})
 
    def add_node(self, parent, nodename):
        node = parent[nodename] = {}
        return node
 
    def add_cell(self, nodename, cellname, value):
        cell =  nodename[cellname] = value
        return cell
 
    def display_dict(self, dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                self.display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1
 
 
def testit():
    # instantiate class
    cd = CreateDict()
 
    # create new dictionary named CityList
    cd.new_dict('CityList')
 
    # add node Boston
    boston = cd.add_node(cd.CityList, 'Boston')
    # add sub node Resturants
    bos_resturants = cd.add_node(boston, 'Resturants')
 
    # Add subnode 'Spoke Wine Bar' to parent bos_resturants
    spoke = cd.add_nimport os
 
class CreateDict:
    """
    Generic Software tools used by Trailmapper.
 
    CreateDict.py - Contains methods to simplify node and cell creation within
                    a dictionary
 
    Usage: 
     
        The best way to learn what can be done is to examine the testit function
        included in this module.
 
        new_dict(dictname) - Creates a new dictionary instance with the name
            contained in dictname
 
        add_node(parent, nodename) - Creates a new node (nested dictionary)
            named in nodename, in parent dictionary.
 
        add_cell(nodename, cellname, value) - Creates a leaf node within node
            named in nodename, with a cell name of cellname, and value of value.
 
        display_dict(dictname) - Recursively displays a nested dictionary.
 
    Requirements:
 
        Trailmapper software:
            None
 
        Python standard library:
            os
     
    Author: Larz60+  -- May 2019.
    """
    def __init__(self):
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
 
    def new_dict(self, dictname):
        setattr(self, dictname, {})
 
    def add_node(self, parent, nodename):
        node = parent[nodename] = {}
        return node
 
    def add_cell(self, nodename, cellname, value):
        cell =  nodename[cellname] = value
        return cell
 
    def display_dict(self, dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                self.display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1
 
 
def testit():
    # instantiate class
    cd = CreateDict()
 
    # create new dictionary named CityList
    cd.new_dict('CityList')
 
    # add node Boston
    boston = cd.add_node(cd.CityList, 'Boston')
    # add sub node Resturants
    bos_resturants = cd.add_node(boston, 'Resturants')
 
    # Add subnode 'Spoke Wine Bar' to parent bos_resturants
    spoke = cd.add_node(bos_resturants, 'Spoke Wine Bar')
    cd.add_cell(spoke, 'Addr1', '89 Holland St')
    cd.add_cell(spoke, 'City', 'Sommerville')
    cd.add_cell(spoke, 'Addr1', '02144')
    cd.add_cell(spoke, 'Phone', '617-718-9463')
 
    # Add subnode 'Highland Kitchen' to parent bos_resturants
    highland = cd.add_node(bos_resturants, 'Highland Kitchen')
    cd.add_cell(highland, 'Addr1', '150 Highland Ave')
    cd.add_cell(highland, 'City', 'Sommerville')
    cd.add_cell(highland, 'ZipCode', '02144')
    cd.add_cell(highland, 'Phone', '617-625-1131')
 
    # display dictionary
    print(f'\nCityList Dictionary')
    cd.display_dict(cd.CityList)
    print(f'\nraw data: {cd.CityList}')
 
if __name__ == '__main__':
    testit()e, 'Addr1', '02144')
    cd.add_cell(spoke, 'Phone', '617-718-9463')
 
    # Add subnode 'Highland Kitchen' to parent bos_resturants
    highland = cd.add_node(bos_resturants, 'Highland Kitchen')
    cd.add_cell(highland, 'Addr1', '150 Highland Ave')
    cd.add_cell(highland, 'City', 'Sommerville')
    cd.add_cell(highland, 'ZipCode', '02144')
    cd.add_cell(highland, 'Phone', '617-625-1131')
 
    # display dictionary
    print(f'\nCityList Dictionary')
    cd.display_dict(cd.CityList)
    print(f'\nraw data: {cd.CityList}')
 

if __name__ == '__main__':
    testit()
testing results:
dialog:
Output:
add data for each user, type 'quit' when done Who are you? Larz60+ Where are you going? Hannaford Grocery What day is it? Sunday What are you buying? Steak How much is the item you are buying? 12.95 How many are you buying? 3 How do you plan to get there? car How much does that cost one way? 1.00 Who are you? Bill Where are you going? Hardware store What day is it? Sunday What are you buying? Bolts How much is the item you are buying? .25 How many are you buying? 10 How do you plan to get there? truck How much does that cost one way? 2.00 Who are you? quit
results
Output:
Larz60+ destination: Hannaford Grocery date: Sunday item: Steak price: 12.95 Quantity: 3.0 vehicle: car commute_codt: 1.0 Bill destination: Hardware store date: Sunday item: Bolts price: 0.25 Quantity: 10.0 vehicle: truck commute_codt: 2.0 Larz60+ Bill destination Hannaford Grocery Hardware store date Sunday Sunday item Steak Bolts price 12.95 0.25 Quantity 3.0 10.0 vehicle car truck commute_codt 1.0 2.0
you will need to add error checking, and add code to prevent crashes.


RE: making variables in my columns and rows in python - snippsat - Oct-31-2021

Add first data i structure eg list, dictionary.
Then can use f-string or eg python-tabulate.
Don't use old string formatting anymore %ds % .
Example.
from tabulate import tabulate

item = 'Milk'
price = 100
quantity = 5
total = 500
item_lst = []
item_lst.append(item)
item_lst.append(price)
item_lst.append(quantity)
item_lst.append(total)

lst = []
header = ['Item', 'Price', 'Quantity', 'Total']
lst.append(header)
lst.append(item_lst)

# f-string
for inner in lst:
    print(''.join((f"{word:<10}" for word in inner)))
print('-' * 35)

# python-tabulate
print(tabulate(lst))
print(tabulate(lst, tablefmt="fancy_grid"))
print(tabulate(lst, tablefmt="github"))
Output:
Item Price Quantity Total Milk 100 5 500 ----------------------------------- ---- ----- -------- ----- Item Price Quantity Total Milk 100 5 500 ---- ----- -------- ----- ╒══════╤═══════╤══════════╤═══════╕ │ Item │ Price │ Quantity │ Total │ ├──────┼───────┼──────────┼───────┤ │ Milk │ 100 │ 5 │ 500 │ ╘══════╧═══════╧══════════╧═══════╛ |------|-------|----------|-------| | Item | Price | Quantity | Total | | Milk | 100 | 5 | 500 |
Also eg Pandas easier to manipulate data eg NoteBook.