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

2024-10-04 13:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

使用此代码:

^{pr2}$

当我需要使用列表变量“catalog”中包含的dict变量时,我必须使用“for循环”,如:

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

这是优雅的吗?在

或者有没有办法给“目录”列表中包含的每个dict变量命名?在

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

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

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


Tags: 文件csvin列表for字典codeitem
2条回答

我的一句话是这样说的:

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

输出:

^{pr2}$

由于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

扩展我在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"] )

或采纳马丁诺的建议: (编辑1:调整以提高优雅度) (EDIT2:修复了错误,使其实际工作正常)

^{pr2}$

相关问题 更多 >