如何命名从 CSV 文件导入的 dict 变量?在 Python

How to name dict variables imported from a CSV file ? in Python

我知道如何从 CSV 文件导入字典类型变量,例如:

code;description;price
c321;white glove;52
d654;orange hat;65
d658;red scarf;85

使用此代码:

import csv

inputfile = open("myfile.csv")
reader_dict = csv.DictReader(inputfile, delimiter=';')

catalog=[]

for line in reader_dict:
    catalog.append(line)

当我需要使用列表变量中包含的 dict 变量时 "catalog" 我必须使用 "for loop" 比如:

for item in catalog:
    if item["code"]=="code I am looking for":
        print ("now can I use the item am interested in!!")

这样优雅吗?

否则有没有办法为 "catalog" 列表中包含的每个字典变量命名?

名称可以是与字典中的键关联的一个值(例如与 "code" 键关联的值),我想自动创建变量,如:

c321 = {'code': 'c321', 'descritpion': 'white glove', 'price':'52'}

如果可能的话,我可以很容易地使用一个带有他名字的变量,而不是每次都使用 "for loop"。

扩展我在 OP 的评论:

It is certainly possible to create such variables, the question is, do you really want to? It is rather un-pythonic, IMHO. Also you would probably have to keep track of all the (variable-)names you created for later use. My suggestion would be to use a (nested) dict, e.g. make your catalog a dictionary and add the records from your csv file with the name of your choice as key.

import csv

catalog = {}
with open("myfile.csv") as inputfile:
  rows = csv.DictReader(inputfile, delimiter=';')
  for row in rows:
    key = row['code']
    catalog[key] = row

print( catalog["some_code"]["description"] )

或采纳martineau的建议: (EDIT1: 进行了调整以提高优雅度) (EDIT2: 修复了错误,因此它实际上按预期工作)

import csv
import collections

catalog = {}
with open("myfile.csv", 'rb') as inputfile:
  row_iterator = csv.reader(inputfile, delimiter=';')
  Record = collections.namedtuple('Record', next(row_iterator))
  # EDIT2: each row is a list here, so we have to use the columnindex to specify the key
  catalog = {row[0]: Record._make(row) for row in row_iterator}    


print( catalog["some_code"].description )

这是我在其中一条评论中的意思:

import csv
import collections

with open("myfile.csv", 'rb') as inputfile:
    reader = csv.reader(inputfile, delimiter=';')
    Record = collections.namedtuple('Record', next(reader))  # use header row
    catalog = [Record._make(row) for row in reader]

for item in catalog:
    print item.code, item.description, item.price

输出:

c321 white glove 52
d654 orange hat 65
d658 red scarf 85

因为catalog仍然是一个list,所以仍然需要一个for循环来顺序访问它的每个元素,但是访问每个元素的字段现在会有点不那么尴尬了。

更新

如果你真的想避免for循环并提前知道代码,你可以做类似下面的事情,它创建一个catalog字典,由第一个字段中的代码值键入每条记录的每个行的其余值映射到嵌套AttrDict字典中的字段名称:

class AttrDict(dict):  # from http://code.activestate.com/recipes/576972-attrdict
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

with open("myfile.csv", 'rb') as inputfile:
    reader = csv.reader(inputfile, delimiter=';')
    fields = next(reader)  # header row
    # row[0] is dict key with remaining values mapped to fieldnames
    catalog = {row[0]: AttrDict(zip(fields[1:], row[1:])) for row in reader}

print catalog
c321 = catalog['c321']
print 'c321:', repr(c321.description), int(c321.price)

输出:

{'c321': {'description': 'white glove', 'price': '52'},
 'd654': {'description': 'orange hat', 'price': '65'},
 'd658': {'description': 'red scarf', 'price': '85'}}
c321: 'white glove' 52