Python Forum
making variables in my columns and rows in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
making variables in my columns and rows in python
#1
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.
Reply
#2
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.
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to store columns of a .csv in variables (when the .csv has no headers) ? hobbyist 6 1,151 Aug-18-2023, 02:06 PM
Last Post: deanhystad
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,175 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  How to properly format rows and columns in excel data from parsed .txt blocks jh67 7 1,802 Dec-12-2022, 08:22 PM
Last Post: jh67
  Check DataFrames with different sorting in columns and rows Foxyskippy 0 753 Nov-19-2022, 07:49 AM
Last Post: Foxyskippy
  The code I have written removes the desired number of rows, but wrong rows Jdesi1983 0 1,603 Dec-08-2021, 04:42 AM
Last Post: Jdesi1983
  rows from sql query need to write to a file as columns sjcsvatt 6 2,336 Oct-09-2021, 12:45 AM
Last Post: snippsat
  Merging spreadsheets with the same columns and extracting rows with matching entries johnbernard 3 8,400 Aug-19-2021, 03:08 PM
Last Post: johnbernard
  Summing up rows and columns plumberpy 3 2,220 Aug-18-2021, 05:46 AM
Last Post: naughtyCat
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 2,083 May-04-2021, 10:51 PM
Last Post: rhat398
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 6,963 Mar-02-2021, 01:54 AM
Last Post: Jeremy7

Forum Jump:

User Panel Messages

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