Home > Blockchain >  converting a string to dot notation to access value in nested list in python
converting a string to dot notation to access value in nested list in python

Time:05-15

items={
         "fruits":
            {
               "summerFruits":
                    {
                        "Mangoes":5,
                        "melon":2
                    }
             }
      }

i converted it to attribute

itemConverted = AttrDict(items)

now i know i can access this by

itemConverted.fruits.summerFruits.Mangoes

but the problem is , i am taking inputs from console as a string so it will be like

wanted="fruits.summerFruits.Mangoes"

i am trying to get it by

itemConverted.wanted

but it is not working , any suggestions

CodePudding user response:

Get the dictionary keys from the string and then use the dictionary items to recover the value.

items={"fruits":{"summerFruits": {"Mangoes":5, "melon":2}}}


def get_val_from_str(string, dct):
    keys = string.split('.')
    v = dct
    for key in keys:
        v = v[key]
    return v

console_input = "fruits.summerFruits.Mangoes"
get_val_from_str(console_input, items)
#5

CodePudding user response:

I could not think of a simple solution with the dictionnary converted through AttrDict. However, here is a basic workaround that works with your input :

items = {"fruits":{"summerFruits":{"Mangoes":5,"melon":2}}}
wanted = "fruits.summerFruits.Mangoes"

#Converts the input to a list of strings (previously separated by dots)
words_list = []
element = ''
for char in wanted:
    if char == '.': #chosen separator for input
        words_list.append(element)
        element = ''
    else:
        element = element   char
words_list.append(element)

#From the dict, get the value at the position indicated by the list of string keys
temp_dict = items
for key in words_list:
    temp_dict = temp_dict.get(key)

value = temp_dict

Hoping this would work for your application, even though the syntax for getting the output is slightly different.

  • Related