【问题标题】:Dictionaries - finding and updating entries from a text file of dictionary information字典 - 从字典信息的文本文件中查找和更新条目
【发布时间】:2023-03-14 01:08:01
【问题描述】:

我正在尝试启用我的代码以允许某人从存储为字典的库存中更新和删除房屋。这是我的代码:

import random
import ast

all_homes = {} #Empty dictionary created to house inventory (get it?)

class Home_Inventory:
    """
    A class for available homes in inventory. 
    Options include adding, modifying, and removing houses. 
    Allows user to output dictionary to text file for ease of reading.
   """

     def __init__(self, sqrft, adr, city, state, zipcode, model, status):
        self.sqrft = sqrft + 'square feet'    # given integer
        self.address = adr
        self.zipcode = zipcode 
        self.city = city
        self.state = state
        self.model = model
        self.status = status #sold/available/contract

    def new_home(self):   # Add a new home to list
        adr = input('Enter street address: ')
        city = input('Enter city: ')
        state = input('Enter two-letter state acronym: ')
        zipcode = int(input('Enter zipcode: '))
        model = input('Enter model name: ')
        sqrft = int(input('Enter whole square feet: '))
        status = input('Is the house available, sold, or under contract?')

        home_attr = {'a':adr, 'c':city, 's':state, 'z':zipcode, 'f':sqrft, 'm':model, 'u':status}
        id_number = random.randint(1000,9999)   # Create an ID number for each house for easy finding
        all_homes[id_number] = home_attr

        print('Home successfully added to database.')

    def del_home(self):  # Delete a sold home from list
        del_home = input('ID number of sold home: ')
        if del_home in all_homes.keys(): # Make sure it exists in list
            del[del_home]
            print('This home has been deleted from database.')
        else:
            print('Not found.')

    def update_home(self):  # Modify attributes of home
        update_home = input('ID number of the house to modify:')

        if update_home in all_homes.keys(): # Make sure it exists in list
            edit_attr = input('Please select attribute to edit\n(f:feet, a: address, c: city, s: state, z: zipcode, m: model, u: status): ')
            updated_attr = input('Please enter updated value: ')
            all_homes[update_home].updatehome_attr(edit_attr, updated_attr)
        else: 
            print('Not found.')

    def output(self):     # Prints text file of listed homes
        f = open("HomeInventory.txt","a")   # Opens (or creates) a text file
        f.write(str(all_homes))   # Writes dictionary to text file
        f.close()   # Closes file

while True:
    print("1. Add a home")
    print("2. Remove a home")
    print("3. Update home")
    print("4. Print inventory")
    print("5. Exit program")
    user_wants=input("What would you like to do today? ")
    if user_wants=="1":
        Home_Inventory.new_home(input)
    elif user_wants=="2":
        Home_Inventory.del_home(input)
    elif user_wants=="3":
        Home_Inventory.update_home(input)
    elif user_wants=="4":
        Home_Inventory.output(input)
        print(all_homes)
    elif user_wants=="5":
        print("\n Thank you for using home inventory.")
        break

特别是:无论我尝试了什么,由于某种原因,我似乎无法更新或删除字典中的家。我输入密钥(ID 号)并不断得到“未找到”结果。

另外,我似乎无法弄清楚如何让字典只允许更新一个属性,因为我什至无法让字典提取找到的地址......我已经添加了ID 号希望更容易找到更新/删除的目标属性,但这似乎没有多大帮助。

另外,我希望能够在每次打开时打开 HomeInventory.txt 文件并将其中已创建的字典读取到程序中,以便用户可以退出程序然后重新进入并修改房屋这是在上一届会议期间提出的,但我不知道该怎么做......非常感谢任何帮助!

【问题讨论】:

  • 好吧,我明白了为什么我无法正确提取字典键 - 我需要确保我传递的是整数而不是字符串作为 ID 号键! :)

标签: python python-3.x dictionary nested


【解决方案1】:

del[del_home] 创建列表[del_home],然后将其删除。不太有用。

你的意思是del all_homes[del_home]

【讨论】:

    【解决方案2】:

    我想通了:

    update_home = input('ID number of the house to modify:')
    

    应该是:

    update_home = int(input('ID number of the house to modify:'))
    

    因为键是整数,而不是字符串。非常简单的修复,让我疯狂了一天!

    对于属性,我更改了编码以使用单个字典作为主属性:

    home_attr = {'a':address, 'c':city, 's':state, 'z':zipcode, 'f':feet, 'm':model, 'u':status}
    

    然后要求用户输入他们要编辑的属性的键,如下所示:

        edit_attr = str(input("Please select attribute to edit\n('f':feet, 'a': address, 'c': city, 's': state, 'z': zipcode, 'm': model, 'u': status): "))
        updated_attr = input('Please enter updated value: ')
        new_home_attr = all_homes[update_home_id]
        new_home_attr[edit_attr] = updated_attr
        all_homes[update_home_id] = new_home_attr
    

    我仍然不知道如何从文本文件中读取字典然后只导入新的字典,但无论如何这超出了课程的范围。

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      相关资源
      最近更新 更多