I have a dictionary like this:
my_dict = {'Southampton': '33.7%', 'Cherbourg': '55.36%', 'Queenstown': '38.96%'}
How can I have a simple plot with 3 bars showing the values of each key in a dictionary?
I've tried:
sns.barplot(x=my_dict.keys(), y = int(my_dict.values()))
But I get :
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict_values'
There are several issues in your code:
my_dict.values()
returns all values as a dict_values
object. int(my_dict.values()))
means converting the set of all values to a single integer, not converting each of the values to an integer. The former, naturally, makes no sense.float("12.34%"[:-1])
.my_dict.keys()
and my_dict.values()
are not guaranteed to return keys and values in the key-value pairs in the same order, for example, the keys you get may be ['Southampton', 'Cherbourg', 'Queenstown']
and the values you get may be "55.36%", "33.7", "38.96%"
.With all these issues fixed:
keys = list(my_dict.keys())
# get values in the same order as keys, and parse percentage values
vals = [float(my_dict[k][:-1]) for k in keys]
sns.barplot(x=keys, y=vals)