-2

Hi Is there some way to use specific keys of a dictionary using matplotlib to plot a graph?

So, my dictionary is the following:

dict= {"USA":234, "ARG":225,
    "SPN": 245, "CAN": 205
    "RO": 345, "MEX": 210}

What I want, is to plot the keys that I specify (with their values), not all of them.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
tuiqs
  • 5
  • 1
  • What have you tried yourself? Please share an example of something you tried and that you expected to work, or your best attempt. What part of the problem are you having trouble with? Selecting elements from a dictionary? Looping over a number of elements? Putting a group of elements on a chart? Creating a specific type of chart? – Grismar Dec 13 '22 at 21:28
  • Delete the keys you don't want. – Danielle M. Dec 13 '22 at 21:28
  • My dictionary is actually way bigger, it has around 20000 keys, so I can't delete the keys I don't want as they are many keys – tuiqs Dec 13 '22 at 21:30
  • **Never** use built-in data types (`dict`), methods, etc., as a variable name, even in a dummy example. – Trenton McKinney Dec 13 '22 at 22:08

2 Answers2

-1

You can filter with a dict comprehension:

d = {"USA":234, "ARG":225,
    "SPN": 245, "CAN": 205,
    "RO": 345, "MEX": 210}
wanted_keys = ['USA', 'ARG']
d_plot = {k:v for k,v in d.items() if k in wanted_keys}

Do not use dict as a variable name for it is a designated word in python.

CodeKorn
  • 300
  • 1
  • 8
-1

Hi try to use the below code:

#import matplotlib and numpy 
import matplotlib.pyplot as plt
import numpy as np
dict= {"USA":234, "ARG":225,
    "SPN": 245, "CAN": 205,
    "RO": 345, "MEX": 210}
# use x as a key of the dict. and y as the value
x=np.array(list(dict.keys()))
y=np.array(list(dict.values()))
# plot x,y and choose the key and value number
plt.plot(x[[0,1,3]],y[[0,1,3]])