简体   繁体   English

从文件索引字典

[英]Indexing a dictionary from file

I am trying to write a code for a simple store that will load products and prices from a file and load it to dictionary and then be able to use it into the program.. but i am trying not to hard code any of the code values so if the file changes it because un-usable. 我正在尝试为一个简单的商店编写代码,该商店将从文件中加载产品和价格并将其加载到字典中,然后能够在程序中使用它。.但是我试图不对任何代码值进行硬编码因此如果文件更改了,因为无法使用。

my file = test.txt contains 我的文件= test.txt包含

banana:3
apple:4

Here what i tried so far 这是我到目前为止尝试过的

d = {}
f = open('test.txt', 'r')
for line in f.readlines():
    name,score = line.split(":")
    d[name] = int(score)

print('''
Welcome to my store
What would you like to buy today

[1] banana
[2] apple
[3] orange

''')

menumain = int(input('Enter product number to continue: '))
if menumain == 1:
    value = int(input('how many banana you will buy'))
    new = d[name][0] * value
    print('You ordered',value,'banana(s), Which will cost you',new )
else:
    print('error! wrong menu')

what i need is 我需要的是

 new = d[name][0] * value

is it modify this line so it auto picks the index.. what user selected and from the product name. 是否修改了该行,以便它自动选择索引?用户选择了什么,并从产品名称中选择了什么。 it use the product's value 它使用产品的价值

in this case index 0 will try to get the value banana which is 3 but it is not working 在这种情况下,索引0将尝试获取值为3的香蕉,但它不起作用

Im doing this because if i write d['banana'] it will work but if something from the outer file is changed the code will break. 我这样做是因为,如果我写d ['banana'],它将起作用,但是如果外部文件中的某些内容被更改,则代码将中断。 So i need something so it works soft-coded 所以我需要一些东西使其可以软编码

You need a list that maps from numbers to product names. 您需要一个从数字映射到产品名称的列表。 You can do: 你可以做:

product_names = d.keys()
print('''
Welcome to my store
What would you like to buy today

''')
for i, p in enumerate(product_names):
    print ("%d) %s" % (i+1, p))
choice = int(input("Enter product number: "))
if i <= len(product_names):
    name = product_names[i+1]
    value = int(input("How many %s do you want to buy: " % name))
    new = d[name] * value
    print("You ordered %d %s(s), which will cost you %d" % (value, name, new))
else:
    print("That's not a valid product number")

It seems like you don't actually want a dict here at all. 似乎您根本不​​需要在这里写字典。 You're trying to access "the first item". 您正在尝试访问“第一项”。 That implies that you want a list: 这意味着您需要一个列表:

lst = {}
f = open('test.txt', 'r')
for line in f.readlines():
    name,score = line.split(":")
    lst.append([name, int(score)])

Now we have a list of pairs, we can get the first one: 现在我们有了一个配对列表,我们可以得到第一个:

lst[0]

… or, if you've asked the user to give you a number: …或者,如果您已要求用户给您提供电话号码,请执行以下操作:

lst[choice]

Of course that's a [name, score] pair, not just a score. 当然,这是一个[name, score]对,而不仅仅是一个分数。 So if you want to get the score, you need another [] : 因此,如果要获得分数,则需要另一个[]

new = lst[choice][1] * value

Looking for something like this? 寻找这样的东西? (Using dict here is not very efficient here) (在这里使用dict并不是很有效)

d = []
f = open('file.txt', 'r')
for line in f.readlines():
    name,score = line.split(":")
    d.append([name,int(score)])

d = sorted(d)

print('''
Welcome to my store
What would you like to buy today

''')

i = 0
for prod in d:
      print("["+str(i+1)+"] "+prod[0])
      i += 1

print("\n")

menumain = int(input('Enter product number to continue: '))
if menumain <= (len(d)-1) and menumain >= 0 :
    prod = d[menumain-1]
    value = int(input('how many '+prod[0]+'(s) you will buy? '))
    print('You ordered '+str(value)+' '+prod[0]+'(s), Which will cost you '+ str(prod[1]*int(value)) )
else:
    print('error! wrong menu')

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

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