A dictionary is another data structure which consists of key-value pairs. It is useful when you want to store named key-value pairs. Keys in a dictionary are unique but values may be duplicate. A single key and value are separated by colon(:) and key-value pairs are separated by a comma(,). A dictionary is created by enclosing key-value pairs between curly braces({ and }).
A dictionary is unordered as opposite to lists and tuples meaning its items cannot be accessed using indexes but only through keys. Examples of dictionary are

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8 }
{ “type” : “smartphone”, “company” : “Samsung”, “screensize” : 5.7}
Above example contains two different dictionaries. It should be noted that values in a dictionary need not be of same type. They can be strings, numbers, floats etc.
Order of items in a dictionary is not maintained. Sometimes, a key-value pair may appear at first position and sometimes the same pair may appear last. That is why it is called unordered and do not provide index based access to its items.

Accessing dictionary items
As mentioned earlier, values of a dictionary can be accessed by using their key names. Syntax to access a value is by using the name of dictionary followed by its key enclosed in square brackets as shown below.

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop)             # print dictionary 
print(laptop["brand"])    # access value with key "brand"
print(laptop["ram"])      # access value with key "ram"
print(laptop["disk"])     # access value with key "disk"

Above code will output

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8 }
Dictionary also contains a method get which can be used to retrieve value of a key. This method takes a string which is the key as an argument and returns the value associated with that key. If there is no value for the given key, or  the key-value pair does not exist it returns None.

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
val = laptop.get("brand")  # get the value for key "brand"
print(val)                 # prints "Leneovo"
val = laptop.get("screen") # get value for non-existent key
print(val)                 # prints "None"

Remember that trying to access an item with a non-existing key using get method will return None and will not be an error. But when accessing a non-existing key using earlier square bracket notation will result in an error as

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop["screen"]) # get value for non-existent key

Above code when executed will result in an error, KeyError: ‘screen’

Modifying dictionary values
It is possible to change the value of a key after the dictionary is created. This is done by assigning updated value to the corresponding key as shown below

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop["brand"])      # prints "Lenovo"
laptop["brand"] = "Apple"   # modify value of key "brand"
print(laptop["brand"])      # prints "Apple"

It is not possible to change a key of dictionary, that is, you cannot change the key “brand” to “model”. Only its value can be modified.

Adding new items to dictionary
For adding a new key-value to a dictionary, same syntax as while updating a value is used except that the key is new. Meaning, in order to add a new item to a dictionary, define the new key and assign it the value you want. Example,

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop)   # print dictionary
laptop["size" : "32 inches"] # create a new key-value pair
print(laptop)   # print updated dictionary

Above code will produce following output

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8}
{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8, “size” : “32 inches” }
Notice, a new key-value pair is added to the dictionary.

Removing items from dictionary
Sometimes it is required to remove a particular key-value from the dictionary. There are three ways of doing that.

1. Using del command: Write the dictionary name followed by the name of key enclosed in square brackets after del command. This will remove this key-value pair from dictionary.

Always remember to provide key name after dictionary when using del. Using just the dictionary name with del will delete the entire dictionary and you will not be able to access it after that.
If you want to remove all key-value pairs from a dictionary and make it empty, then call clear method in the dictionary object.

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop)      # print dictionary
del laptop["ram"]  # remove item with key "ram"
print(laptop)      # print again
laptop.clear()     # remove all items
print(laptop)      # print empty dictionary
del laptop         # remove entire dictionary
print(laptop)      # print dictionary again   

Above program will give the following output. Notice the error message at the last line. This is because we are accessing the dictionary after deleting it. Also, a blank line in between indicates an empty dictionary since clear method was called before that.

{‘brand’: ‘Lenovo’, ‘disk’: ‘320GB’, ‘ram’: 8}
{‘brand’: ‘Lenovo’, ‘disk’: ‘320GB’}

NameError: name ‘laptop’ is not defined

2. Using pop method: pop method takes a string as argument which represents the key of item to be removed. Example,

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop)      # print dictionary
laptop.pop("disk")  # remove item with key "disk"
print(laptop)      # print again

Output will be

{ “brand” : “Lenovo”, “disk” : “320GB”, “ram” : 8 }
{ “brand” : “Lenovo”, “ram” : 8}

Notice the item with key “disk” is removed.

3. Using popitem method: popitem method removes the last inserted key-value pair from the dictionary. It also returns the item removed. Example,

laptop = { "brand" : "Lenovo", "disk" : "320GB", "ram" : 8 } # create dictionary
print(laptop)                 # print dictionary
laptop["screen"]= "32 inches" # add a new item with key "screen"
item = laptop.popitem()       # remove last inserted item
print(item)                   # prints "{ 'screen', '32 inches'}"


Mark Your Impression

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.