python - 使用字典,练习代码

标签 python dictionary python-3.3

对于我之前提出的问题,我深表歉意,因为这些问题含糊不清且难以回答。我对编程还很陌生,并且仍在学习它的来龙去脉。所以请耐心听我说。现在介绍背景信息。我正在使用 python 3.3.0。我已将其加载到 Eclipse IDE 中,这就是我用来编写代码并进行测试的地方。

现在回答问题:我正在尝试学习如何创建和使用字典。因此,我的任务是创建一个价格匹配代码,该代码通过用户界面不仅能够在字典中搜索项目(即键以及与键关联的值的位置和价格)。我已经创建了一个用户界面,它将运行得足够好,不会出现任何错误(至少在 IDE 中),当我运行并输入所有提示时,空字典不会更新,因此我无法调用早期输入的字典。

我有到目前为止在下面编写的代码,希望有人能告诉我我是否正确地做事。如果有更好的方法来解决这个问题。我仍在学习,因此有关代码术语的更详细解释会很有用。

print("let's Price match") 
decition = input("Are you adding to the price match list?") 
if decition == "yes": 
    pricematchlist = {"Snapple":["Tops",99]} 
    location = input("Now tell me where you shopped") 
    item = input("Now what  was the item") 
    price = input("Now how much was the item") 
    int(price) 
    pricematchlist[item]=location,price 
    print(pricematchlist) 
else:  
    pricematchlist = {"Snapple":["Tops",99]}  
    reply = input("Ok so you want to search up a previous price?") 
    if reply == "yes": 
        search = input("What was the item?")
        pricematchlist.item(search)

最佳答案

这些是一些细微的变化。对于字典:您正确使用它们。

print("let's Price match") 
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes": 
    # pricematchlist = {"Snapple":["Tops",99]}
    # If this whole code block is called repeatedly, you don't want to reassign it
    location = input("Now tell me where you shopped") 
    item = input("Now what  was the item") 
    price = int(input("Now how much was the item"))
    # int(price) does nothing with reassigning price
    pricematchlist[item]=location,price 
    print(pricematchlist) 
else:    
    reply = input("Ok so you want to search up a previous price?").lower()
    if reply == "yes": 
        search = input("What was the item?")
        print pricematchlist[search] # easier way of accessing a value

关于python - 使用字典,练习代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15852757/

相关文章:

python - 如何在 PyCharm IDE 中使用子进程模块调用基于 ncurses 的应用程序?

python - 使用 xml.etree 在 Python 中编写包含欧元符号 (€) 的 xml 文件

python - 如何用 python 对字典中的数组的值求和?

Python-机器学习: Creating a training and test set from a list of arrays

python - 如何从纯文本中捕获字典键?

python - 在 openSUSE 上安装最新的 Python

Python 3.5 使用 pyinstaller 生成的可执行文件创建 .rpm

python - 'SELECT LAST_INSERT_ID()' 处的语法错误

python - 使用 python 3.3 时是否需要 python 包 virtualenv?

python - 查找词频 - 无需计数器