Vandexel
Vandexel

Reputation: 639

Python dictionary manipulation from dot notation

What I want to do is create a "dictionary pathway" from a string. I don't think that's the right term, but basically, if i have a dictionary that looks like this:

'myDict'{
    'classes':{
        'students':{
            'grades':{
                'grade':'A'
            }
        }  
    }
}

and I have a variable called current_dict that has myDict in it right now, so current_dict = myDict, and a string stored as "classes.students.grades", I would like to manipulate that string so that I have [classes][students][grades]. However, I want to be able to use that to reassign current_dict. So, I would like to say current_dict = myDict['classes']['students']['grades']. I tried turning the string into "[classes][students][grades]", but that doesn't work, because it identifies the whole thing as a single string, including the brackets. How can I manipulate "classes.students.grades" so that I can reassign current_dict = myDict['classes']['students]['grades']? So, after I have done this, current_dict would be grades and would look like:

{
    grade': 'A'
}

Upvotes: 0

Views: 171

Answers (2)

Michael Brothers
Michael Brothers

Reputation: 3

Try this:

string1='classes.students.grades'
string2=string1.split('.')
myDict[string2[0]][string2[1]][string2[2]]['grade2']='B'
myDict

my output was

{'classes': {'students': {'grades': {'grade1': 'A', 'grade2': 'B'}}}}

Note that I changed grade to grade1 in my dictionary. Why not use a pandas DataFrame?

Upvotes: 0

L3viathan
L3viathan

Reputation: 27283

Something like this?

current_dict = myDict
mystring = "classes.students.grades"
myPath = mystring.split(".")
for part in myPath:
    current_dict = current_dict[part]

But I think there's probably a much easier way to do this, if you just tell us what you want this for.

Upvotes: 1

Related Questions