想要从 csv 文件创建键值对列表但无法

Want to create a key value pair list from csv file but unable to

我想使用 /getService 路由的输出创建一个键值对列表。

我可以从 csv 文件 vet_service_locations 中过滤我想要的数据(郊区和服务),但我想将其作为键值对。其中键是郊区,服务和值将是相关输出。

我是初学者,尝试过不同的方法,但似乎没有任何效果。

from bottle import html_quote, route, run, template, response, request
import petl as etl
from json import dumps
import csv


output = []

reading_file = etl.fromcsv('vet_service_locations.csv')
print(reading_file)


@route('/getServices')
def details():
    postcode = request.query.postcode
    print(postcode)
    for row in reading_file:
        if row[2] == postcode:
            output.append(row[1])
            output.append(row[4])
            
    print(output)
        
    

run(host='localhost', port=3000, debug=True)

Vet_service_location.csv data image is in this link

我得到的输出

[('Adelaide', 'Small_Animal'), ('Adelaide', 'Oncology'), ('Adelaide', 'Surgery'), ('Adelaide', 'Annual_Checkup'), ('Adelaide', 'Wildlife')]

我想要的输出

 suburb, values 
[('Adelaide', 'Small_Animal'),  
('Adelaide', 'Oncology'),  
('Adelaide', 'Surgery'),  
('Adelaide', 'Annual_Checkup'),  
('Adelaide', 'Wildlife')]

所以,有点像 table,与 vet_service_locations.csv 的结构相同。

如果您希望 output 成为以 suburb 为键,service 为值的键值对列表,那么您应该替换行

output.append(row[1])
output.append(row[4])

只有 output.append((row[1], row[4])),所以 output 是一个元组列表。

或者,您可能想制作 output 字典。为此,请将声明 output = [] 替换为 output = {},然后替换行

output.append(row[1])
output.append(row[4])

output[row[1]] = row[4].

除了@Andrew 的回答,尝试pprint输出你想要的格式。

import pprint

# ...
    # ...
    for row in reading_file:
        if row[2] == postcode:
            output.append((row[1], row[4]))
    
    print("suburb, values")    
    pprint.pprint(output)

输出

suburb, values
[('Adelaide', 'Small_Animal'),
 ('Adelaide', 'Oncology'),
 ('Adelaide', 'Surgery'),
 ('Adelaide', 'Annual_Checkup'),
 ('Adelaide', 'Wildlife')]

或者,如果您希望输出类似于 table,请尝试使用格式化字符串文字/ f-strings.

# ...
    # ...
    sub_width = val_width = 0
    for row in reading_file:
        if row[2] == postcode:
            output.append((row[1], row[4]))
       
            # calculate the minimum width of each column
            sub_width = len(row[1]) if len(row[1]) > sub_width else sub_width
            val_width = len(row[4]) if len(row[4]) > val_width else val_width


    print(f"+{'='*(sub_width+2)}+{'='*(val_width+2)}+")
    print(f"| {'Suburb':{sub_width}} | {'Service':{val_width}} |")
    print(f"+{'='*(sub_width+2)}+{'='*(val_width+2)}+")
    for row in output:
        print(f"| {row[0]:{sub_width}} | {row[1]:{val_width}} |")
        print(f"+{'-'*(sub_width+2)}+{'-'*(val_width+2)}+")

输出

+==========+================+
| Suburb   | Service        |
+==========+================+
| Adelaide | Small_Animal   |
+----------+----------------+
| Adelaide | Oncology       |
+----------+----------------+
| Adelaide | Surgery        |
+----------+----------------+
| Adelaide | Annual_Checkup |
+----------+----------------+
| Adelaide | Wildlife       |
+----------+----------------+

或者,输出也可以馈送到 template 并返回为 HTML table。您可以将需要的任何数据作为模板变量传递给 template。只要模板使用相同的变量名称,您就可以随意命名变量。

template(filepath, var1=data1, var2=data2, ...)

假设您有以下项目结构

project-name
 |-- views
 |    |-- index.tpl
 |  ...
 |-- main.py

修改您的 Python 脚本

# ...
    # ...
    for row in reading_file:
        if row[2] == postcode:
            output.append((row[1], row[4]))

    return template('views/index.tpl', title="Available Vet Service", header=["Suburb", "Values"], rows=output)

index.tpl

的内容
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link 
     rel="stylesheet" 
     href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
     integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
     crossorigin="anonymous"
    >
    <title>{{title}}</title>
  </head>
  <body>
    <div>
      <table class="table table-striped table-hover table-responsive-sm">
        <thead class="thead-dark">
          <tr>
            % for col_title in header:
              <th scope="col">{{col_title}}</th>
            % end
          </tr>
        </thead>
        <tbody>
          % for cell in rows:
            <tr>
              <td>{{cell[0]}}</td>
              <td>{{cell[1]}}</td>
            </tr>
          % end
        </tbody>
      </table>
    </div>
  </body>
</html>

这是 HTML 输出的屏幕截图。