Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a nested dictionary in this format

{'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': {'label': 1}, 'C_course-v1:TsinghuaX+30240243X+sp': {'label': 1}}, 'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': {'label': 1}}

How do I change it to this

{'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': 1}, 'C_course-v1:TsinghuaX+30240243X+sp': 1}, 'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': 1}
question from:https://stackoverflow.com/questions/65641174/changing-the-value-of-a-nested-dictionary-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
76 views
Welcome To Ask or Share your Answers For Others

1 Answer

I would suggest a recursive function

So go through the dictionary and check whether the value for some key is also a dictionary, if it is, call the function again, else check whether the key is "label" then call the function again on the value an return it

my_dict = {
    "U_1003076": {
        "C_course-v1:TsinghuaX 34100325_X sp": {"label": 1},
        "C_course-v1:TsinghuaX 30240243X sp": {"label": 1},
    },
    "U_1019796": {"C_course-v1:TsinghuaX 30240184 sp": {"label": 1}},
}
def solution(my_dict):
    if type(my_dict) is not dict: return my_dict
    for k,v in my_dict.items():
        if type(v) is dict:
            my_dict[k]=solution(v)
        elif k=="label":
            return solution(v)
    return my_dict

print(solution(my_dict))
{
    "U_1003076": {
        "C_course-v1:TsinghuaX 34100325_X sp": 1,
        "C_course-v1:TsinghuaX 30240243X sp": 1,
    },
    "U_1019796": {"C_course-v1:TsinghuaX 30240184 sp": 1},
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...