# Plot a Python Dictionary in Order of Key Values

Muhammad Waiz Khan Mar-08, 2021 Jan-25, 2021 Python Python Dictionary

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:

## Related Article - Python Dictionary

• Check if a Key Exists in a Dictionary in Python
• Convert a Dictionary to a List in Python
• Get All the Files of a Directory
• Find Maximum Value in Python Dictionary
• Delete a File and Directory in Python
• Sort a Python Dictionary by Value