Home > Net >  I have a question about my coding homework about lists and dictionaries. Can anyone help explain wha
I have a question about my coding homework about lists and dictionaries. Can anyone help explain wha

Time:10-25

I have a question about my coding homework about lists and dictionaries. I understand up until question 4, and that is where I get stuck. Can anyone help explain what to do?

  1. Creates a list.

  2. Alters the contents of the list.

  3. Extracts one item from the list and saves it as a variable.

  4. Stores the value in a dictionary with a key pointing to it.

  5. Adds more key-value pairs to the dictionary.

  6. Retrieves and prints the stored dictionary value by accessing it with a key.

    animals = ['cat', 'dog', 'chicken', 'horse', 'pig']
    animals.remove('dog')
    print(animals)
    horse = animals[2:3]
    print(horse)
    

CodePudding user response:

You can get the horse item by specifying only it's index, there is no need to use slicing like you did:

horse = animals[3]

A dictionary in python is simply a key-value pair container which associates each unique key with only one value for example:

dictionary = dict()
dictionary['animal'] = horse

Here we created a dictionary using the dict() method and created a key-value pair which associates the key 'animal' with the value being the horse variable and you can do the same process to add more key-value pairs.

And to retrieve the value associated with a key then you can use this simply:

print(dictionary['animal'])

This will print the value associated with the 'animal' key.

CodePudding user response:

I would try to avoid telling you the exact answer. Instead, I am going to explain what each term in the question means.

Your step 3 solution is not correct. You should extract one item and save it as a variable, not to extract a segment of the list.

Here is how you get one value:

value = my_list[ind]

Here is how you get a sublist:

sublist = my_list[begin_ind_inclusive, end_ind_exclusive]

Your step 4 did not explicitly say what key you should use, so I would assume your teach just wants you to use any key you like.

Here is how you create a dictionary:

my_dict = {}

Here is how you add a key-value pair to a dictionary:

my_dict[key] = value # Here key, value can be variable or constant (e.g., 'horse')

Here is how you get a value from dictionary by its key:

value = my_dict[key] # Assuming key is already in dictionary
  • Related