Which method can be used to add a key-value pair to a dictionary?

Master Python with the PCAP Certification! Explore interactive quizzes and detailed explanations to ensure your exam success. Gain confidence and get certified!

The method that correctly adds a key-value pair to a dictionary is the update() method. This method allows you to add new key-value pairs or modify existing keys in a dictionary. When you pass another dictionary or iterable of key-value pairs to update(), it will merge that data into the original dictionary.

For instance, if you have a dictionary called 'my_dict' and you want to add a new pair, you can use 'my_dict.update({"new_key": "new_value"})'. This modifies 'my_dict' directly by adding or updating the specified key.

The other choices are not appropriate for this purpose. The append() method is used with lists to add an element, while put() is not a built-in method for dictionaries in Python. The add() method is commonly associated with sets and is not applicable to dictionaries, making update() the valid choice for adding key-value pairs to a dictionary.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy