Home > front end >  How can I get an element of a list nested in a dictionary according to user input?
How can I get an element of a list nested in a dictionary according to user input?

Time:04-15

I've been playing around with dictionaries and what they can do, when using a list as a value, I can't retrieve the list according to a user's input let alone an element within the list. All I get is 'TypeError: unhashable type: 'dict' The code used was:

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)

However, when I use a more direct method to retrieve the list or an element within the list, I get the desired result.

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)

Is this because the user input method stores the entire dictionary not the name of the dictionary as a string (or int, float, etc.)? if so, how can I retrieve a list element according to a user's input?

CodePudding user response:

You are calling the same key for the main dict and the inner (nested) dict, but obviously in your example this can not work and you should ask a new key.

Moreover you return the inner (nested) dict, so you should change the getting_the_list function.

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)
  • Related