pythonpython-3.xmatplotlibcurrency-exchange-rates

Make graph from dictionary in Python


Unable to create a graph using Matplotlib whilst using this dictionary. Trying to be able to choose the two values, then produce a graph.

Eg. select USD and GBP and plot graph.

import matplotlib.pyplot as plt

exchange_rates = {
    "GBP": {
    "USD": 1.2,
    "EUR": 1.1
},
"USD": {
    "GBP": 1.18,
    "EUR": 1.07
},
"CZK": {
    "GBP": 28.7934,
    "EUR": 29.654,
    "USD": 40.345
    }
}
def make_a_graph():
    plt.bar(range(len(exchange_rates)), exchange_rates.values())
    plt.xticks(range(len(exchange_rates)), list(exchange_rates.keys()))
    plt.show()

Solution

  • In your code, exchange_rates is a dictionnary which itself contains dictionnaries. You should do double dereferencing in order to plot the values.

    def make_a_graph(exchange_rates):
        x=len(exchange_rates["CZK"])
        y1=exchange_rates["CZK"]  
        plt.bar(range(x),y1.values())
        plt.show()
    

    Note you have to be consistent with the length of the quantities you want to plot. I have plotted only one key above.