[英]Python: csv file to dictionary
那是我的csv文件(import_inventory.csv)內容:
ruby , rope , ruby , gold coin , ruby , axe
純文本。 CSV文件與我的腳本位於同一文件夾中。
我要打開它,然后將其添加到“ inv”字典中:
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1}
我必須使用該函數作為默認函數並對其進行定義(這是我的練習):
def import_inventory(inventory, filename="import_inventory.csv"):
接下來,我需要像這樣打印它:
Inventory:
count item name
----------------
45 gold coin
12 arrow
6 torch
2 dagger
1 rope
1 ruby
----------------
Total number of items: 67
我有一個名為“ print_table”的函數,它正在為我做類似的事情。 這只是為了讓您知道,目前的問題僅在於打開csv文件並將其與現有字典“ inv”合並
提前致謝。 如果有不清楚的地方,請告訴我!
我認為這應該做您想要的。 如果字典中不存在某一項,則必須創建一個值為1的該項。 在所有其他情況下,您只需要添加一個即可。
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)
我將使用上下文管理器以更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
defaultdict的好處是您不必在增加庫存前檢查您的物品是否存在。 Python defaultdict為您做到了。
該函數運行三個步驟:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.