Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Dictionaries in python
  5. Working with Dictionaries

Working with Dictionaries

Working with dictionaries means three basic operation on dictionaries i.e., updating dictionary, adding elements to a dictionary and deleting elements of a dictionary.

Updating Dictionary:-

We can change the value of an existing key by using assignment.
syntax:-

dictionary_name[key]=new_value

e.g.,

a={'1':'python', '2':'Java','3':'JavaScript','4':'C'}
a['4']='C++'
print(a)
Output- {'1':'python', '2':'Java','3':'JavaScript','4':'C++'}

Adding elements to a dictionary:-

We can add elements by updating the dictionary with a new key and then assigning the value to a new key.
syntax:-

dictionary_name[key]=value

e.g.,

a={}
a['1']='Python'
print(a)
Output- {'1': 'Python'}

Deleting elements from a dictionary:-

To delete a key-value pair in a dictionary we can use del method. A disadvantage is that it gives KeyError if we try to delete a non-existence key.
syntax:-

del dictionary_name['key']

e.g.,

a={'1' :'python', '2' :'Java','3' :'JavaScript','4':'C', '5':'C++'}
del a['3']
print(a)
Output {'1' :'python', '2' :'Java','4':'C', '5':'C++'}

This is how we work in dictionaries in python.

Was this article helpful to you? Yes No

How can we help?