Computer Science
How do you add key:value pairs to an existing dictionary?
Python Dictionaries
CBSE
2 Likes
Answer
There are three ways by which new key:value pairs can be added to an existing dictionary:
1. By using assignment as per the following syntax:
<dictionary>[<key>] = <value>
For example:
d = {1 : 'a' , 2 : 'b'}
d[3] = 'c'
print(d)
Output
{1: 'a', 2: 'b', 3: 'c'}
2. By using update() method:
update() method merges key:value pairs from new dictionary into the original dictionary adding or replacing as needed. The syntax to use this method is:
<dictionary>.update(<other-dictionary>)
For example:
d = {1 : 'a' , 2 : 'b'}
d.update({3 : 'c'})
print(d)
Output
{1: 'a', 2: 'b', 3: 'c'}
3. Using setdefault() method:
It inserts a new key:value pair only if the key doesn't already exist. If the key already exists, it returns the current value of the key. The syntax to use this method is:
<dictionary>.setdefault(<key>,<value>)
For example:
d = {1 : 'a' , 2 : 'b'}
d.setdefault(3,'c')
print(d)
Output
{1: 'a', 2: 'b', 3: 'c'}
Answered By
1 Like
Related Questions
What do you understand by ordered collection and unordered collection ? Give examples.
Can you remove key:value pairs from a dictionary and if so, how?
Can you change an element of a sequence or collection? What if a collection is a dictionary? What if a sequence is a string?
Which of the following types qualify to be the keys of a dictionary?
- String
- tuple
- Integer
- float
- list
- dictionary