Advertisement
acclivity

pyDictionaryExample

Jan 29th, 2021 (edited)
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.92 KB | None | 0 0
  1. # Demonstration script for handling a Dictionary in Python, used as a mini database
  2. # Mike Kerry - Jan 2021 - acclivity2@gmail.com
  3.  
  4. # This dictionary will be indexed by Musical Artist
  5. # Each Artist entry will hold a list of Albums by that artist
  6. # Album data will include Date of Release and the medium (e.g. EP/LP/CD/MP3/Video)
  7.  
  8. # Example format of the Dictionary
  9. # {'BEATLES': ['Beatles', ['ABBEY ROAD', 'Abbey Road', '1969', 'CD'], ['LET IT BE', 'Let It Be', '1970', 'CD'], ['HELP', 'Help', '1965', 'LP']],
  10. # 'WHO': ['Who', ['MY GENERATION', 'My Generation', '1965', 'CD'], ['WHO', 'Who', '2019', 'CD']],
  11. # 'FRANK SINATRA': ['Frank Sinatra', ['MY WAY', 'My way', '1969', 'LP']]}
  12.  
  13. # The dictionary data will be backed up in a CSV file, with one line per album
  14. # Beatles,Abbey Road,1969,CD
  15. # Beatles,Let It Be,1970,CD
  16. # Beatles,Help,1965,LP
  17. # Who,My Generation,1965,CD
  18. # Who,Who,2019,CD
  19. # Frank Sinatra,My way,1969,LP
  20.  
  21.  
  22. def normalise_artist(p_artist):
  23.     # This routine can be used if required, to remove "The " off the front of an Artist name
  24.     # Then, for example, "The Beatles" and "Beatles" are treated as the same group
  25.     p_artist = p_artist.title()
  26.     if p_artist.upper()[:4] == "THE ":
  27.         return p_artist[4:]
  28.     return p_artist
  29.  
  30.  
  31. def add_artist(p_artist):
  32.     global music_dict
  33.  
  34.     # We will make the Artist Key all upper-case to avoid case discrepancies on look-up
  35.     p_artist_key = p_artist.upper()
  36.  
  37.     if p_artist_key not in music_dict:
  38.         # Create a new entry. For now it only contains the original form of the artist name
  39.         music_dict[p_artist_key] = [p_artist]
  40.         return True
  41.     else:
  42.         return False            # Return False to say add was not possible
  43.  
  44.  
  45. def add_album(p_artist, p_album, p_date, p_medium):
  46.     global music_dict
  47.  
  48.     # Make the album key all upper case
  49.     p_artist_key = p_artist.upper()
  50.     p_album_key = p_album.upper()
  51.     t_artist_data = music_dict[p_artist_key]
  52.     # The above statement extracts all the data held for one artist into a list named t_artist_data
  53.     # This list holds the original artist name, followed by a sub-list with  one entry per album
  54.     # Example: ['Who', ['MY GENERATION', 'My Generation', '1965', 'CD'], ['WHO', 'Who', '2019', 'CD']]
  55.     # Existing albums are elements 1 upwards within the artist data
  56.     for t_idx in range(1, len(t_artist_data)):
  57.         t_alist = t_artist_data[t_idx]
  58.         if t_alist[0] == p_album_key:       # Does the album name we want to add already exist?
  59.             return False                    # - yes - return saying add failed
  60.     t_artist_data += [[p_album_key, p_album, p_date, p_medium]]     # append a new sub-list to the artist data
  61.     music_dict[p_artist_key] = t_artist_data    # insert the extended data back into the database for this artist
  62.     return True                             # Return a flag saying album was added successfully
  63.  
  64.  
  65. music_dict = {}
  66.  
  67. # Read text file (CSV format) and build Dictionary
  68.  
  69. fin = open("MusicData.txt")
  70. for lina in fin:
  71.     lina = lina.strip()
  72.     splita = lina.split(",")
  73.     if len(splita) < 3:
  74.         continue                # Ignore incomplete lines
  75.     for x, el in enumerate(splita):
  76.         splita[x] = el.strip()
  77.  
  78.     # Extract the parts from one album line
  79.     artist = splita[0].title()
  80.     artist = normalise_artist(artist)
  81.     album = splita[1]
  82.     date = splita[2]
  83.     medium = splita[3]
  84.     print(artist, album, date, medium)
  85.  
  86.     # Add this album to our dictionary
  87.     add_artist(artist)
  88.     add_album(artist, album, date, medium)
  89.  
  90.  
  91. fin.close()
  92. print(music_dict)
  93.  
  94. while True:
  95.     print("1. Add new artist")
  96.     print("2. Add new album")
  97.     print("3. List albums for an artist")
  98.     print("4. Find album")
  99.     print("9. Quit")
  100.     option = input("Choose an option: ")
  101.     if option == "1":
  102.         # New artist
  103.         artist = input("Enter Artist name: ")
  104.         artist = normalise_artist(artist)
  105.         res = add_artist(artist)
  106.         if res is False:
  107.             print("That artist is already in the database")
  108.         else:
  109.             print("Artist", artist, "added to database")
  110.  
  111.         continue
  112.  
  113.     if option == "2":
  114.         artist = input("Enter Artist for this album: ")
  115.         artist = normalise_artist(artist)
  116.         artist_key = artist.upper()
  117.         if artist_key not in music_dict:
  118.             print("That artist is not in the database")
  119.             continue
  120.         album = input("Enter Album Name: ")
  121.         album_key = album.upper()
  122.         date = input("Enter Release Date: ")
  123.         medium = input("Enter Medium (EP/LP/CD: ")
  124.  
  125.         res = add_album(artist, album, date, medium)
  126.  
  127.         if res is False:
  128.             print("That album is already in the database")
  129.         else:
  130.             print("Album has been added")
  131.  
  132.         continue
  133.  
  134.     if option == "3":
  135.         artist = input("Enter Artist Name: ")
  136.         artist = normalise_artist(artist)
  137.         artist_key = artist.upper()
  138.         if artist_key not in music_dict:
  139.             print("That artist is not in the database")
  140.             continue
  141.         # List albums for the artist
  142.         artist_data = music_dict[artist_key]
  143.         # artist_data contains original artist name + a list of lists of albums
  144.         # Existing albums are elements 1 upwards within the artist data
  145.         for idx in range(1, len(artist_data)):
  146.             alist = artist_data[idx]
  147.             album = alist[1]
  148.             date = alist[2]
  149.             medium = alist[3]
  150.             print(artist.ljust(15), album.ljust(20), date.ljust(8), medium.ljust(6))
  151.  
  152.     if option == "4":
  153.         # Search all Artists for an Album name
  154.         album = input("Enter Album Name: ")
  155.         album_key = album.upper()
  156.         found = False
  157.         for artist_key in music_dict.keys():
  158.             artist_data = music_dict[artist_key]
  159.             for x in range(1, len(artist_data)):
  160.                 album_data = artist_data[x]
  161.                 if album_data[0] == album_key:
  162.                     found = True
  163.                     artist = artist_data[0]
  164.                     album = album_data[1]
  165.                     date = album_data[2]
  166.                     medium = album_data[3]
  167.                     print(artist.ljust(15), album.ljust(20), date.ljust(8), medium.ljust(6))
  168.  
  169.         if not found:
  170.             print("No album named", album, "was found")
  171.  
  172.     if option == "9":
  173.         # Quit. Write the dictionary back out to the text file in CSV format
  174.         fout = open("MusicData.txt", 'w')
  175.         for artist_key in music_dict.keys():
  176.             artist_data = music_dict[artist_key]
  177.             artist = artist_data[0]
  178.             for x in range(1, len(artist_data)):
  179.                 album_data = artist_data[x]
  180.                 album = album_data[1]
  181.                 date = album_data[2]
  182.                 medium = album_data[3]
  183.                 outline = ",".join([artist, album, date, medium]) + "\n"
  184.                 fout.write(outline)
  185.         fout.close()
  186.         break               # Quit
  187.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement