KnowledgeBoat Logo

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