[英]I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python)
[英]How do I compare the strings in a txt.file to my dictionary values (the values are integers) and calculate the sum
我的問題的標題可能有點混亂 - 也許那是因為我自己有點困惑。
我的任務是為餐廳創建一個小型計費系統(它不是真正的餐廳)。 我有 3 個文本文件。 第一個是 menu.txt。 在文件中,每一行都包含一道菜的名稱和價格,用逗號分隔。 然后我有 2 個訂單文件 order1.txt 和 order2.txt 每行都包含已訂購的菜單中的一項。
我自己對這項任務的建議是將菜單文件放入列表中,然后使其成為字典。
這是我的解決方案:
def compute_total(mfile, ofile):
dictionary = {}
newlist = []
with open('menu.txt') as f:
for line in f:
line = line.replace(',', '')
newlist.append(line.split())
for strings in newlist:
dictionary[strings[0]] = strings[1]
我覺得我做對了,但我真的不知道如何從這里制作代碼。 因為我知道我想以某種方式查看例如: order1 是否在字典(菜單)中,然后計算菜餚的價值(價格)。
我在想下面可能是這樣的,但它不起作用,我被卡住了。
for k, v in dictionary.items():
if int(k) in dictionary.items():
Dvalues.append(v)
我希望你能給我一些建議,讓我繼續前進。 我是一個新手,所以我真的希望你能花一些時間來幫助我解決這樣的小問題(對你來說)。
最好的問候,見
Python 的csv
package 非常適合處理逗號分隔的文件。 csv 模塊不必手動解析每一行,而是能夠將每一行轉換為以前用逗號分隔的值列表。 然后,您可以使用並行分配來獲取每行的商品和價格,並將它們存儲在字典中:
with open('menu.txt') as f:
for line in f:
item, price = csv.reader(line, quotechar="'", delimiter=",")
dictionary[item] = price
現在您已經在字典中存儲了所有菜單項,您所要做的就是從其他文本文件中讀取每個項目行,將該項目傳遞給您的字典,取回價格,並將其添加到總和中:
order1_total = 0
with open(mfile) as f:
for line in f:
item = line
order1_total += dictionary[item]
不要忘記將行import csv
添加到程序的頂部。 希望能幫助到你! 祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.