Guest User

Untitled

a guest
Oct 1st, 2026
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. import json
  2.  
  3. class Item:
  4. def __init__(self, id, description):
  5. self.id = id
  6. self.description = description
  7.  
  8. def state(self):
  9. """Return a dictionary describing the item internals."""
  10.  
  11. return {"id": self.id, "description": self.description}
  12.  
  13. def __str__(self):
  14. return f"Item(id='{self.id}', description='{self.description}')"
  15.  
  16. # this is so Items IN A SEQUENCE are printed nicely
  17. def __repr__(self):
  18. return str(self)
  19.  
  20. id2obj = {} # the mapping dictionary,
  21. inventory = [] # the inventory list
  22.  
  23. item1 = Item("axe1", "An Elven axe")
  24. id2obj["axe1"] = item1
  25. inventory.append(item1.id)
  26.  
  27. item2 = Item("book2", "A very old book with a cracked red cover")
  28. id2obj["book2"] = item2
  29. inventory.append(item2.id)
  30.  
  31. print(f"{inventory=} # note the inventory is just strings")
  32.  
  33. # list what's in the inventory
  34. # this shows how to use the 'id2obj' dictionary to *dereference* the 'id'
  35. print("\nDescriptions of items in the inventory:")
  36. for id in inventory:
  37. print(" ", id2obj[id].description)
  38.  
  39. # let's save the inventory list and the two items in a JSON file
  40. # we create a single list with two elements, a list of 'state' dictionaries
  41. # for each item and the inventory list itself
  42. json_file = "save.json"
  43. save_data = [[item1.state(), item2.state()], inventory]
  44. with open(json_file, "w") as fd:
  45. fd.write(json.dumps(save_data))
  46.  
  47. print(f"\nJSON file '{json_file}' created.")
  48.  
  49. print("\n############ Saving and restoring data\n")
  50.  
  51. # now load the data back from JSON and recreate the Items, inventory and
  52. # the id->object dictionary
  53. with open(json_file) as fd:
  54. json_data = fd.read()
  55.  
  56. print(f"Restored {json_data=}")
  57.  
  58. # recreate the Items and the dictionary mapping id -> reference to object
  59. (new_item_dicts, new_inventory) = json.loads(json_data)
  60. print(f"\nRestored python data:\n {new_item_dicts=}\n {new_inventory=}")
  61.  
  62. # create the new Item instances, store in list, create the mapping dictionary
  63. new_items = []
  64. new_id2obj = {}
  65. for item_dict in new_item_dicts:
  66. i = Item(**item_dict)
  67. new_items.append(i)
  68. new_id2obj[i.id] = i
  69.  
  70. print("\nRestored Items and mapping dictionary:")
  71. print(f" {new_items=}")
  72. print(f" {new_id2obj=}")
  73.  
  74. # print the descriptions of items in the new inventory using the new Items
  75. # and the new mapping dictionary
  76. print("\nNow print the recovered Items descriptions:")
  77. for id in new_inventory:
  78. print(" ", new_id2obj[id].description)
  79.  
Advertisement
Add Comment
Please, Sign In to add comment