Learn

There are two methods for removing specific elements from a set:

  1. The .remove() method searches for an element within the set and removes it if it exists, otherwise, a KeyError is thrown.

    # Given a list of song tags song_tags = {'guitar', 'acoustic', 'folk', 'country', 'live', 'blues'} # Remove an existing element song_tags.remove('folk') print(song_tags) # Try removing a non-existent element song_tags.remove('fiddle')

    Would output:

    {'blues', 'acoustic', 'country', 'guitar', 'live'}

    Followed by:

    Traceback (most recent call last):
    File "some_file_name.py", line 9, in <module>
     song_tags.remove('fiddle')
    KeyError: 'fiddle'
  2. The .discard() method works the same way but does not throw an exception if an element is not present.

    # Given a list of song tags song_tags = {'guitar', 'acoustic', 'folk', 'country', 'live', 'blues'} # Try removing a non-existent element but with the discard method song_tags.discard('guitar') print(song_tags) # Try removing a non-existent element but with the discard method song_tags.discard('fiddle') print(song_tags)

    Would output:

    {'folk', 'acoustic', 'blues', 'live', 'country'} {'folk', 'acoustic', 'blues', 'live', 'country'}

Note that items cannot be removed from a frozenset so neither of these methods would work.

Instructions

1.

Some users have created tags that are not related to music, and you’d like to get rid of them. For now, let’s manually remove the incorrect tags.

To start off, we need another set for the tag data within song_data_users. Create a set called tag_set and store the tag data for 'Retro Words'.

2.

Now we need to remove the tags which are unrelated to music. In this case, remove the tags: 'onion', 'helloworld', and 'spam'.

3.

For the last step, replace the value of the key, 'Retro Words' inside of song_data_users so that it is equal to the updated tag set.

Print song_data_users to see the results.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?