pythontabulate

Python Tabulate a dictionary without raw data


I am trying to print a table of values of a function. If X is 1 then Y would be something like 4, so in a Column all X values and in Y all the solutions. For this. I am using an eval that solves the string equation, the program asks for number of range for X, named as "RANGO". Then it sums x + 1 and calculates the eval, then, again, until the loop is finished within the range. The problem is, the dictionary its created well, but, in the tabulate, it inserts the RAW Data of the Dictionary. So here is how my program looks right now:

import re
from tabulate import tabulate

def funcion():
  
 while True:
   global funcion
   
   funcion = input("Introduce una Funcion. ")
   
   if re.match('.[a-zA-Z].' ,funcion) and not re.match("[x1-9]", funcion):
    print("Incorrecto, contiene una letra")
     
   elif "x" not in funcion:
      print("No contiene la X necesaria en una funcion: ")
     
   else: 
     rango = int(input("Introduce la cantidad de valores de Y que quieres sacar: "))
     
     if re.match("(\d+)x", funcion):
      funciont = re.sub(r'(x)', r'*\1', funcion)
      for x in range(rango):
          x = x + 1
          print(eval(funciont), "= Y", "x = ",x)
        
     else: #CREO LOS DICCIONARIOS
      s = {}
      r = {}
      for x in range(rango): #PARA X EN RANGO ESPECIFICADO,SE SUMA 1
       x = x + 1 #SE DEFINE X EN CADA CICLO, MAS UNO
       s["{0}".format(x)] = eval(funcion)
       r["{0}".format(x)] = x
       print(x)
      break
#CON DARLE VALOR A X EL EVAL AUTO CAMBIA X POR EL VALOR DE ELLA.
 global tabla
 tabla = [["Val Y", "Val X"],[s, r]]
 print(tabulate(tabla, headers='firstrow', tablefmt='fancy_grid'))
 
 
funcion()    

As you can see, the tabulate looks like this: TABLE

And I want it to look like this:

╒══════════════╤═══════════════╕
│ X            │       y       │
╞══════════════╪═══════════════╡
│ 1            │         6     │
├──────────────┼───────────────┤
│ 2            │          12   │
├──────────────┼───────────────┤
│ 3            │         18    │
├──────────────┼───────────────┤
│ 4            │          24   │
╘══════════════╧═══════════════╛

Solution

  • tabulate needs list

    tabula = [ ['X', 'Y'], [1, 6], [2, 12], [3, 18], [4, 24] ]
    

    Instead of dictionaries r,s you could use normal list to keep rows with [x, y]

    rows = []
    

    and later use

    rows.append([x, eval(funcion)])
    

    and finally create table

    tabla = [ ["Val Y", "Val X"] ] + rows
    

    Full working example:

    import re
    from tabulate import tabulate
    
    def funcion():
    
        rows = []
        
        while True:
      
            #func = input("Introduce una Funcion. ")
            func = 'x * 6'
            print(' func:', func)
            
            if re.match('.[a-zA-Z].', func) and not re.match("[x1-9]", func):
                print("Incorrecto, contiene una letra")
             
            elif "x" not in func:
                print("No contiene la X necesaria en una funcion: ")
             
            else: 
                #rango = int(input("Introduce la cantidad de valores de Y que quieres sacar: "))
                rango = 5
                print('rango:', rango)
                
                if re.match("(\d+)x", func):
                    func = re.sub(r'(x)', r'*\1', func)
                    for x in range(1, rango+1):
                        print(eval(func), "= Y", "x =", x)
                
                else:
                    for x in range(1, rango+1):
                        rows.append([x, eval(func)])
                    break
    
        tabla = [["X", "Y"],] + rows
     
        print(tabulate(tabla, headers='firstrow', tablefmt='fancy_grid'))
     
    # --- execute ---
    
    funcion()
    

    Result:

     func: x * 6
    rango: 5
    ╒═════╤═════╕
    │   X │   Y │
    ╞═════╪═════╡
    │   1 │   6 │
    ├─────┼─────┤
    │   2 │  12 │
    ├─────┼─────┤
    │   3 │  18 │
    ├─────┼─────┤
    │   4 │  24 │
    ├─────┼─────┤
    │   5 │  30 │
    ╘═════╧═════╛
    

    EDIT:

    If you need r,s for other calculations then you can convert to rows using:

    rows = []
    
    for x, y in zip(r.values(), s.values()):
        rows.append( [x, y] )