当我试图打印dict时出现打字错误

2024-10-03 04:36:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张我想画的纸条:

my_dict={'a': 0.015015015015015015,
 'b': 2.0,
 'c': 0.0,
 'd-e': 0.14,
 'f': 0.0
 nan: 0.06
}

此代码给出了一个错误

import matplotlib.pylab as plt

lists = sorted(my_dict.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

-> TypeError: '<' not supported between instances of 'float' and 'str'

而另一个

plt.bar(list(my_dict.keys()), list(my_dict.values()))

返回错误

-> TypeError: 'value' must be an instance of str or bytes, not a float

我该怎么画呢


Tags: ofmy错误notpltnanfloatdict
1条回答
网友
1楼 · 发布于 2024-10-03 04:36:48

问题在于plot期望数字能够绘制。所以你可以这么做

x, y = zip(*lists) # unpack a list of pairs into two tuples

x_num = np.arange(len(x)) # Numbers to plot

plt.plot(x_num, y)
plt.xticks(x_num, labels=x) # Replace x_num with your labels in x
plt.show()

得到

Plot

如果字典中有一个np.nan作为键,您可以随时用另一个最适合您的键替换它:

my_dict['not nan'] = my_dict.pop(np.nan) # Replace

# Plot
lists = sorted(my_dict.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.bar(list(my_dict.keys()), list(my_dict.values()))

得到

bar plot

相关问题 更多 >