Append (key: value) Pair to DictionaryDictionary is one of the most used data types in Python. It is an unordered collection of key: value pairs. Every value has a corresponding key that identifies it. A dictionary is a mutable collection, meaning we can modify the values. One factor that makes a dictionary unique among other data types is that it stores the mapping of key: value pairs while other data types store a single value as an element. Example:Output: {101: 'Ramya', 102: 'Sanya', 103: 'Sree'} Ramya Sanya Sree Given that a dictionary is mutable, we should be able to alter the values of existing keys and add new key: value pairs to the dictionary. This tutorial discusses how we can add a new key: value pair, into a dictionary. 1. The Traditional way of using the key Subscripts:We can assign the existing keys with the values we want. Python forgets the old value and updates the new value to the key. Using the same way, we can assign values to new keys, thus appending new pairs. Example: Output: {101: 'Ramya', 102: 'Sanya', 103: 'Sree'} {101: 'Ramya', 102: 'Priyanka', 103: 'Ujjwala', 104: 'Sanya', 105: 'Sree'} 2. update() Method:It is an inbuilt dictionary method designed to modify a dictionary. The method takes the {key: value} pair as an argument and adds it to the dictionary.
Example: Output: {101: 'Ramya', 102: 'Sanya', 103: 'Sree'} {101: 'Ramya', 102: 'Priyanka', 103: 'Ujjwala', 104: 'Sanya', 105: 'Sree'}
What if we want to add thousands of new key: value pairs?
Example: Output: The original dictionary: {101: 'Ramya', 102: 'Sanya', 103: 'Sree'} New key: value pairs: {104: 'Jeevani', 105: 'Rishitha', 106: 'Nikitha'} The updated dictionary: {101: 'Ramya', 102: 'Sanya', 103: 'Sree', 104: 'Jeevani', 105: 'Rishitha', 106: 'Nikitha'} 3. The OOPS Way:
Example: Output: #updating existing key: {101: 'Ramya', 102: 'Sanya', 103: 'Sree'} Enter the key you want to modify: 102 Enter the value to update: Priyanka {101: 'Ramya', 102: 'Priyanka', 103: 'Sree'} #adding new key:value pair: {101: 'Ramya', 102: 'Sanya', 103: 'Sree'} Enter the key you want to modify: 104 Enter the value to update: Sanya {101: 'Ramya', 102: 'Sanya', 103: 'Sree', 104: 'Sanya'}
Example:
Next Topicany() in Python
|
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week