蟒蛇;获取字典的长度作为字典中的值

时间:2019-08-25 11:45:44

标签: python dictionary python-3.6

我会在字典中添加一个值,该值包含字典的长度,例如:

所以我基本上尝试了

{..., 'commands' : len(dict) + ' commands are available'}

但是它重新播放了NameError: name 'dict' is not defined

我也尝试过

def dict_len():
     return len(dict)
{..., 'commands' : dict_len() + ' commands are available'}

但是:NameError: name 'dict' is not defined

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

首先,请不要使用dict作为变量名,它已经是一个类,因此请不要覆盖它。

第二,您要先保存字典,就像这样

my_dict = {...} # put whatever values you have in here

然后做

my_dict["commands"] = str(len(my_dict)) + " commands are available"

答案 1 :(得分:-1)

您没有将参数传递给您定义的函数

def len_dict(dict):
       return len(dict)

这就是您必须使用这些功能的方式。

我认为您需要了解python的基础知识。