Cr1t1c

Indexing Python nested dictionaries

Sep 22nd, 2021
934
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #1. create empty dictionary
  2. heroes = {}
  3.  
  4. print(heroes)
  5. #2. add nested dictionary for dc characters
  6. heroes = {"DC": {"Batman": "Bruce Wayne", "Green Arrow": "Oliver Queen", "Green Lantern": "Hal Jordan", "Superman": "Clark Kent", "The Flash": "Barry Allen"}}
  7.    
  8. #3. add nested dictionary for marvel characters
  9. heroes["Marvel"] = {}
  10. heroes2 = {"Black Panther": "TChalla",      "Captain America": "Steve Rogers",      "Daredevil": "Matt Murdock", "Deadpool": "Wade Wilson", "Spider-Man": "Peter Parker"}
  11.  
  12. heroes["Marvel"].update(heroes2)
  13.  
  14. print(heroes)
  15. #4. Update the nested dictionary
  16. heroes["Marvel"]["Black Panther"] = "T'Challa"
  17.  
  18. #5. Creat user input to check real name
  19.  
  20. name = input("Enter hero name: ")
  21.  
  22. if name in heroes["DC"]:
  23.    print(name,"is",heroes["DC"][name], end=".\n")
  24. elif name in heroes["Marvel"]:
  25.     print(name,"is",heroes["Marvel"][name], end=".\n")
  26. else:
  27.     print("No such hero.")
RAW Paste Data