如何根据用户输入获取嵌套在字典中的列表元素



我一直在研究字典以及它们的功能,当使用列表作为值时,我无法根据用户的输入检索列表,更不用说列表中的元素了。我得到的只是"TypeError:不可破解类型:"dict"使用的代码是:

dictionary = {'dictA': {'keyA': [1, 2, 3]}, 'dictB': {'keyB': [4, 5, 6]}}
#retrieving the the list from provided key#
def getting_the_list(nested_dict, key):
values = dictionary[nested_dict][key]
return values
#retrieving the nested dictionary according to user input#
def nested_dict(nested_dict):
dict_in_dict = dictionary[nested_dict]
return dict_in_dict
#having user choose dict#
inPut = input('which dict?n')
nested_dict = nested_dict(inPut)
value = getting_the_list(nested_dict, inPut)
print(value)

然而,当我使用更直接的方法来检索列表或列表中的元素时,我会得到所需的结果。

dictionary = {'dictA': {'keyA': [1, 2, 3]}}

#retrieving the the list from provided key#
def getting_the_list(nested_dict, key):
values = dictionary[nested_dict][key]
return values

values = getting_the_list('dictA', 'keyA')
print(values)

这是因为用户输入法将整个字典存储起来,而不是将字典的名称存储为字符串(或int、float等(吗?如果是,我如何根据用户的输入检索列表元素?

您正在为主dict和内部(嵌套(dict调用相同的键,但在您的示例中,这显然不起作用,您应该请求一个新的键。

此外,您还返回了内部(嵌套(dict,因此应该更改getting_the_list函数。

dictionary = {"dictA": {"keyA": [1, 2, 3]}, "dictB": {"keyB": [4, 5, 6]}}
# retrieving the the list from provided key#
def getting_the_list(nested_dict, key):
values = nested_dict[key]
return values

# retrieving the nested dictionary according to user input#
def nested_dict(nested_dict):
dict_in_dict = dictionary[nested_dict]
return dict_in_dict

# having user choose dict#
input_out = input("which dict?n")
input_nested = input("which inner key?n")
nested_dict = nested_dict(input_out)
value = getting_the_list(nested_dict, input_nested)
print(value)

最新更新