我知道如何从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循环”。在
我的一句话是这样说的:
输出:
^{pr2}$由于
catalog
仍然是一个list
,因此仍然需要一个for
循环来顺序访问它的每个元素,但是访问每个元素的字段现在就不那么麻烦了。在更新
如果您真的想避免
for
循环并提前知道代码,可以执行以下操作,创建一个catalog
字典,该字典由每个记录的第一个字段中的代码值键入,而每行的其余值映射到嵌套的AttrDict
字典中的字段名:输出:
扩展我在OP的评论:
或采纳马丁诺的建议: (编辑1:调整以提高优雅度) (EDIT2:修复了错误,使其实际工作正常)
^{pr2}$相关问题 更多 >
编程相关推荐