简体   繁体   English

Python:将csv文件转换为字典

[英]Python: csv file to dictionary

That's my csv file (import_inventory.csv) content: 那是我的csv文件(import_inventory.csv)内容:

ruby ,  rope ,  ruby  , gold coin ,  ruby  , axe

Plain text. 纯文本。 Csv file is in the same folder as my script. CSV文件与我的脚本位于同一文件夹中。

I want to open it, next add that items to my "inv" dictionary: 我要打开它,然后将其添加到“ inv”字典中:

inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1}

I must use that function as default and define it (Thats my exercice): 我必须使用该函数作为默认函数并对其进行定义(这是我的练习):

def import_inventory(inventory, filename="import_inventory.csv"):

Next I need to print it just like that: 接下来,我需要像这样打印它:

Inventory:
 count    item name
   ----------------
    45    gold coin
    12        arrow
     6        torch
     2       dagger
     1         rope
     1         ruby
    ----------------
  Total number of items: 67

I have function called "print_table" That is doing something like that for me. 我有一个名为“ print_table”的函数,它正在为我做类似的事情。 That's just for letting You know that problem for now is only with opening csv file and merging it with existing dictionary "inv" 这只是为了让您知道,目前的问题仅在于打开csv文件并将其与现有字典“ inv”合并

Thanks in advance. 提前致谢。 If something is unclear, please let me know! 如果有不清楚的地方,请告诉我!

I think that should do what you want. 我认为这应该做您想要的。 If an item does not exist in the dictionary you have to create this item with a value of one. 如果字典中不存在某一项,则必须创建一个值为1的该项。 In all other cases you just have to add one. 在所有其他情况下,您只需要添加一个即可。

   def import_inventory(inventory, filename="import_inventory.csv"):
        file = open(filename, 'r')
        data = file.readline().split(',')
        inv = inventory
        for item in data:
            item = item.strip()
            if item in inv:
                inv.update({item: inv[item]+1})
            else:
                inv.update({item: 1})
        return inv

    def print_table(inventory):
        inv = inventory
        count = 0
        print('{:>5} {:>15}'.format('count', 'item name'))
        print('---------------------')
        for item in inv:
            print('{:>5} {:>15}'.format(inv[item], item))
            count = count + inv[item]
        print('---------------------')
        print('Total number of items: ' + str(count))


    given_inventory = {'sword': 100, 'rope': 4}
    new_inventory = import_inventory(given_inventory)
    print_table(new_inventory)

I would design import_inventory in a more pythonic way with a context manager for interacting with plain text files and a defaultdict for counting the stock. 我将使用上下文管理器以更Python化的方式设计import_inventory ,以与纯文本文件进行交互,并使用defaultdict来计算库存。

from collections import defaultdict
from contextlib import suppress

def import_inventory(inventory, filename):
    _inventory = defaultdict(int)
    with open(filename, encoding="UTF_8") as stream:
        for line in stream:
            for item in line.split(","):
                stock = inventory.get(item.strip(), 0)
                with suppress(KeyError):
                    del(inventory[item.strip()])
                _inventory[item.strip()] += stock + 1
    return _inventory

The interest of defaultdict is you don't have to check if your item is present or not before increasing the stock. defaultdict的好处是您不必在增加库存前检查您的物品是否存在。 Python defaultdict does it for you. Python defaultdict为您做到了。

The function runs three steps: 该函数运行三个步骤:

  1. Get the current stock for the read item. 获取已读项目的当前库存。 Initialize it to 0 if there isn't any stock for that item. 如果该项目没有库存,则将其初始化为0。
  2. Remove the item from the current inventory in order to get the current stock only once. 从当前库存中删除物料,以便仅获取一次当前库存。 Monitor KeyError exception with the suppress feature. 使用抑制功能监视KeyError异常。
  3. Increment the new stock into _inventory (without checking if the item is already present). 将新库存增加到_inventory中 (无需检查项目是否已存在)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM