Python Dictionary

A dictionary is key-value pair datatype written in curly brackets. Dictionary is unordered and changeable. Keys must be unique in the dictionary but the value may not be. You can access the dictionary value by its key.

Create Dictionary:

>>> dix = {}                   # Build a dict by starting with the empty dict {}
>>> dix['a'] = 'green'         # storing key-value pairs into dict
>>> dix['b'] = 'red'
>>> dix['c'] = 'yellow'
>>> dix
{'a': 'green', 'b': 'red', 'c': 'yellow'}

>>> dix = {'fruit':'apple','color':'red','shape':'circle','quantity':50}
>>> dix
{'quantity': 50, 'shape': 'circle', 'fruit': 'apple', 'color': 'red'}

Access Element: Used key to access its element. You can also use dict.get(key) method to get the value of the specified key.

>>> dix['shape']
circle

>>> dix.get('color')
red

Change Element: change the value of a specific element by defining its key.

>>> dix['color'] = 'green'
>>> dix
{'quantity': 50, 'shape': 'circle', 'fruit': 'apple', 'color': 'green'}

Add Element: Add element by new index key with assigning value to it.

>>> dix['quality'] = 'A-grade'
>>> dix
{'quantity': 50, 'shape': 'circle', 'quality': 'A-grade', 'fruit': 'apple', 'color': 'green'}

Removing Element:

  • dict.pop(key) –  removes and return the element with the specified key name
  • del – removes the element with the specified key name. It also used to delete the entire dictionary.
  • dict.clear() – used to empty the dictionary
>>> fruit_dix = {'fruit':'apple','color':'red','shape':'circle','quantity':50}

>>> fruit_dix.pop('shape')
'circle'
>>> fruit_dix
{'color': 'red', 'quantity': 50, 'fruit': 'apple'}

>>> del fruit_dix['quantity']
>>> fruit_dix
{'color': 'red', 'fruit': 'apple'}

>>> fruit_dix.clear()
>>> fruit_dix
{}                             # Empty dictionary

Loop through a Dictionary:

>>> fruit_dix = {'fruit':'apple','color':'red','shape':'circle','quantity':50}
# Print all keys of a dictionary
>>> for e in fruit_dix:
...     print(e)
fruit
color
shape
quantity
# print all values of a Dictionary
>>> for e in fruit_dix:
...     print(fruit_dix[e])
apple
red
circle
50
# print all values of a Dictionary
>>> for e in fruit_dix.values():
...     print(e)
apple
red
circle
50

Check Key exists in Dictionary: Using in and not in membership operator check the specified key exist in the dictionary or not.

>>> fruit_dix = {'fruit':'apple','color':'red'}
>>> if 'color' in fruit_dix: 
...     print("Key exists in dictionary")
Key exists in dictionary

.     .     .

Function Description
len(dix) Gives the total number of elements in a dictionary
dict.copy() Make a copy of a dictionary
dict.get(key) Returns the value of the specified key
dict.items() Returns a list of dict‘s (key, value) tuple pairs
dict.keys() Returns a list of all key of a dictionary
dict.values() Return a list of all values of a dictionary
>>> fruit_dix = {'fruit':'apple','color':'red','shape':'circle','quantity':50}

>>> fruit_dix.keys()           # Returns a list of all key of a dictionary
dict_keys(['fruit', 'color', 'shape', 'quantity'])

>>> fruit_dix.values()         # Return a list of all values of a dictionary
dict_values(['apple', 'red', 'circle', 50])

>>> fruit_dix.items()          # Returns a list of dict's (key, value) tuple pairs
dict_items([('fruit', 'apple'), ('color', 'red'), ('shape', 'circle'), ('quantity', 50)])

# print both key & values of a Dictionary
>>> for key,val in fruit_dix.items():
...     print(f'{key} ==> {val}')
fruit ==> apple
color ==> red
shape ==> circle
quantity ==> 50

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials