fork download
  1. music = {
  2. "Band 1": {
  3. "Album A": ["1-Track A1", "1-Track A2", "1-Track A3"],
  4. "Album B": ["1-Track B1", "1-Track B2", "1-Track B3"],
  5. "Album C": ["1-Track C1", "1-Track C2", "1-Track C3"]
  6. },
  7. "Band 2": {
  8. "Album A": ["2-Track A1", "2-Track A2", "2-Track A3"],
  9. "Album B": ["2-Track B1", "2-Track B2", "2-Track B3"],
  10. "Album C": ["2-Track C1", "2-Track C2", "2-Track C3"]
  11. },
  12. "Band 3": {
  13. "Album A": ["3-Track A1", "3-Track A2", "3-Track A3"],
  14. "Album B": ["3-Track B1", "3-Track B2", "3-Track B3"],
  15. "Album C": ["3-Track C1", "3-Track C2", "3-Track C3"]
  16. }
  17. }
  18.  
  19. import random
  20. def pick_track(music_collection):
  21. # we must pick a key and look that up if we get a dictionary
  22. if isinstance(music_collection, dict):
  23. chosen = music_collection[random.choice(list(music_collection.keys()))]
  24. else:
  25. chosen = random.choice(music_collection)
  26.  
  27. if isinstance(chosen, str): # it's a string, so it represents a track
  28. return chosen
  29. else: # it's a collection (list or dict) so we have to pick something from inside it
  30. return pick_track(chosen)
  31.  
  32.  
  33. def pick_track2(music_collection):
  34. if isinstance(music_collection, dict):
  35. random_key = random.choice(list(music_collection.keys()))
  36. else:
  37. random_key = random.randrange(len(music_collection))
  38. chosen = music_collection[random_key]
  39. if isinstance(chosen, str):
  40. return [random_key, chosen]
  41. else:
  42. return [random_key] + pick_track2(chosen)
  43.  
  44. for i in range(5):
  45. print(pick_track(music))
  46.  
  47. for i in range(5):
  48. print("Band: '{}' - Album: '{}' - Track {}: '{}'".format(*pick_track2(music)))
  49.  
Success #stdin #stdout 0.03s 12360KB
stdin
Standard input is empty
stdout
1-Track B1
3-Track B2
3-Track C2
3-Track A1
2-Track A3
Band: 'Band 1' - Album: 'Album C' - Track 1: '1-Track C2'
Band: 'Band 2' - Album: 'Album B' - Track 0: '2-Track B1'
Band: 'Band 1' - Album: 'Album B' - Track 0: '1-Track B1'
Band: 'Band 3' - Album: 'Album B' - Track 2: '3-Track B3'
Band: 'Band 3' - Album: 'Album B' - Track 2: '3-Track B3'