如何用Python编写这个片段?

mor*_*ous 2 python postgresql

我正在学习Python(我有一个C/C++背景).

我需要在学习的同时用Python编写实用的东西.我有以下伪代码(我第一次尝试编写Python脚本,因为昨天阅读了Python).希望该片段详细说明了我想要做的事情的逻辑.BTW我在Ubuntu Karmic上使用python 2.6.

假设脚本被调用为:script_name.py directory_path

import csv, sys, os, glob

# Can I declare that the function accepts a dictionary as first arg?
def getItemValue(item, key, defval)
  return !item.haskey(key) ? defval : item[key]


dirname = sys.argv[1]

# declare some default values here
weight, is_male, default_city_id = 100, true, 1 

# fetch some data from a database table into a nested dictionary, indexed by a string
curr_dict = load_dict_from_db('foo')

#iterate through all the files matching *.csv in the specified folder
for infile in glob.glob( os.path.join(dirname, '*.csv') ):
  #get the file name (without the '.csv' extension)
  code = infile[0:-4]
  # open file, and iterate through the rows of the current file (a CSV file)
  f = open(infile, 'rt')
  try:
    reader = csv.reader(f)
    for row in reader:
      #lookup the id for the code in the dictionary
      id = curr_dict[code]['id']
      name = row['name']
      address1 = row['address1']
      address2 = row['address2']
      city_id = getItemValue(row, 'city_id', default_city_id)

      # insert row to database table

  finally:
    f.close()
Run Code Online (Sandbox Code Playgroud)

我有以下问题:

  1. 代码是用Pythonic编写的(有没有更好的实现方法)?

  2. 给定一个具有如下所示的模式的表,我如何编写一个Python函数,从表中获取数据并返回在由string(name)索引的字典中.

  3. 如何将行数据插入表中(实际上我想尽可能使用事务,并在文件关闭之前提交)

表模式:

create table demo (id int, name varchar(32), weight float, city_id int);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我的后端数据库是postgreSQL

[编辑]

Wayne等人:

为了澄清,我想要的是一组行.每一行都可以用键索引(这意味着行容器是一个字典(右)?好了,现在一旦我们使用键检索了一行,我也希望能够访问'列'中的'行 - 意味着行数据本身就是一个字典.我不知道Python在处理字典时是否支持多维数组语法 - 但是下面的语句将有助于解释我打算如何在概念上使用从db返回的数据. dataset ['joe'] ['weight']将首先获取由键'joe'(这是一个字典)索引的行数据,然后将该字典索引为键'weight'.我想知道如何构建这样的以你之前的Pythonic方式从检索到的数据中获取字典字典.

一种简单的方法是写下这样的东西:

import pyodbc

mydict = {}
cnxn = pyodbc.connect(params)
cursor = cnxn.cursor()
cursor.execute("select user_id, user_name from users"):

for row in cursor:
   mydict[row.id] = row
Run Code Online (Sandbox Code Playgroud)

这是正确的/可以用更加pythonic的方式写吗?

Sil*_*ost 5

要从字典中获取值,您需要使用以下.get方法dict:

>>> d = {1: 2}
>>> d.get(1, 3)
2
>>> d.get(5, 3)
3
Run Code Online (Sandbox Code Playgroud)

这将消除对getItemValue功能的需求.我不会评论现有的语法,因为它显然与Python不同.Python中三元的正确语法是:

true_val if true_false_check else false_val
>>> 'a' if False else 'b'
'b'
Run Code Online (Sandbox Code Playgroud)

但正如我在下面所说,你完全不需要它.

如果您使用的是Python> 2.6,则应使用以下with语句try-finally:

with open(infile) as f:
    reader = csv.reader(f)
    ... etc
Run Code Online (Sandbox Code Playgroud)

看到你想拥有row字典,你应该使用csv.DictReader而不是简单csv. reader.但是,在您的情况下,这是不必要的.您的sql查询可以构造为访问rowdict 的字段.在这种情况下,你不会需要创建单独的项目city_id,name等等.为了默认添加city_idrow,如果不存在,你可以使用它.setdefault的方法:

>>> d
{1: 2}
>>> d.setdefault(1, 3)
2
>>> d
{1: 2}
>>> d.setdefault(3, 3)
3
>>> d
{1: 2, 3: 3}
Run Code Online (Sandbox Code Playgroud)

而且id,简单地说row[id] = curr_dict[code]['id']

切片时,您可以跳过0:

>>> 'abc.txt'[:-4]
'abc'
Run Code Online (Sandbox Code Playgroud)

一般来说,Python的库提供fetchone,fetchmany,fetchall上光标的方法,它返回Row的对象,这可能支持类似字典的访问或返回一个简单的元组.这取决于您使用的特定模块.