# Python - How To Plot a Python Dictionary in Order of Key Values

ID : 201

viewed : 203

Tags : PythonPython Dictionary

99

This tutorial explains how we can plot a dictionary in Python using the `pyplot` module of `matplotlib` library of Python. We will plot the dictionary in `key-value` pair, where x-axis of the plot will be the key of the dictionary and the y-axis will be the value of the dictionary.

## Plot a Python Dictionary Using the `pyplot` Module of `matplotlib` Library

The code example below converts the dictionary into a list of key-value pairs, then sorts it using the `sorted` function so that our graph is ordered. After sorting, `x` and `y` values are extracted from the list using the `zip` function.

After getting the x and y axesâ€™ values, we could pass them as arguments to the `plt.plot` function for graph plotting.

Example code:

``import matplotlib.pylab as plt  my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}  myList = my_dict.items() myList = sorted(myList)  x, y = zip(*myList)   plt.plot(x, y) plt.show() ``

Output:

We can also add labels to the x-axis and y-axis and a title to the graph. The code example below shows how we can add them to the graph.

``import matplotlib.pylab as plt  my_dict = { 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1}  myList = my_dict.items() myList = sorted(myList) x, y = zip(*myList)  plt.plot(x, y) plt.xlabel('Key') plt.ylabel('Value') plt.title('My Dictionary') plt.show() ``

Output: