Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- class Item:
- def __init__(self, id, description):
- self.id = id
- self.description = description
- def state(self):
- """Return a dictionary describing the item internals."""
- return {"id": self.id, "description": self.description}
- def __str__(self):
- return f"Item(id='{self.id}', description='{self.description}')"
- # this is so Items IN A SEQUENCE are printed nicely
- def __repr__(self):
- return str(self)
- id2obj = {} # the mapping dictionary,
- inventory = [] # the inventory list
- item1 = Item("axe1", "An Elven axe")
- id2obj["axe1"] = item1
- inventory.append(item1.id)
- item2 = Item("book2", "A very old book with a cracked red cover")
- id2obj["book2"] = item2
- inventory.append(item2.id)
- print(f"{inventory=} # note the inventory is just strings")
- # list what's in the inventory
- # this shows how to use the 'id2obj' dictionary to *dereference* the 'id'
- print("\nDescriptions of items in the inventory:")
- for id in inventory:
- print(" ", id2obj[id].description)
- # let's save the inventory list and the two items in a JSON file
- # we create a single list with two elements, a list of 'state' dictionaries
- # for each item and the inventory list itself
- json_file = "save.json"
- save_data = [[item1.state(), item2.state()], inventory]
- with open(json_file, "w") as fd:
- fd.write(json.dumps(save_data))
- print(f"\nJSON file '{json_file}' created.")
- print("\n############ Saving and restoring data\n")
- # now load the data back from JSON and recreate the Items, inventory and
- # the id->object dictionary
- with open(json_file) as fd:
- json_data = fd.read()
- print(f"Restored {json_data=}")
- # recreate the Items and the dictionary mapping id -> reference to object
- (new_item_dicts, new_inventory) = json.loads(json_data)
- print(f"\nRestored python data:\n {new_item_dicts=}\n {new_inventory=}")
- # create the new Item instances, store in list, create the mapping dictionary
- new_items = []
- new_id2obj = {}
- for item_dict in new_item_dicts:
- i = Item(**item_dict)
- new_items.append(i)
- new_id2obj[i.id] = i
- print("\nRestored Items and mapping dictionary:")
- print(f" {new_items=}")
- print(f" {new_id2obj=}")
- # print the descriptions of items in the new inventory using the new Items
- # and the new mapping dictionary
- print("\nNow print the recovered Items descriptions:")
- for id in new_inventory:
- print(" ", new_id2obj[id].description)
Advertisement
Add Comment
Please, Sign In to add comment