Add new keys to dictionary in Python

We can add an item to existing dictionary in Python using following methods.

Method1: Using update method of dictionary:

1. Create dictionary:

>>> countries={'United States of America':'Washington','Canada':'Ottawa','India':'New Delhi'} >>> countries {'United States of America': 'Washington', 'Canada': 'Ottawa', 'India': 'New Delhi'}

2. Add another country and its capital to above dictionary

>>> countries.update({'China':'Beijing'}) >>> counties {'United States of America': 'Washington', 'Canada': 'Ottawa', 'India': 'New Delhi', 'China': 'Beijing'}

Method2: By adding key and values

3. Add new item like dictionary[‘key’]=’value’.

>>> countries['Germany']='Berlin' #Add country Germany and its capital >>> countries {'United States of America': 'Washington', 'Canada': 'Ottawa', 'India': 'New Delhi', 'China': 'Beijing', 'Germany': 'Berlin'}

Method3: Add new keys to dictionary in Python using __setitem__ method

4. Add new item using method __setitem__ :

>>> countries.__setitem__('Japan','Tokyo') # Add country Japan and its capital to exisitng dictionary >>> countries {'United States of America': 'Washington', 'Canada': 'Ottawa', 'India': 'New Delhi', 'China': 'Beijing', 'Germany': 'Berlin', 'Japan': 'Tokyo'}

Related Posts

Responses are currently closed, but you can trackback from your own site.

Comments are closed.

Powered by k2schools
%d bloggers like this: