Home > Enterprise >  Get certain part of a dict
Get certain part of a dict

Time:10-18

I need to get a certain part of a dict. The part I need is in bold and I'm not sure how i can get to this (I need to do this on other keys as well as this is just one key)

{" Complete the following statement: changing state from ---(1)--- to gas is known as ---(2)---.": {"['1: liquid; 2: evaporation', '1: liquid; 2: melting', '1: solid; 2: evaporation', '1: solid; 2: melting']": "1: liquid; 2: evaporation", "['1: liquid; 2: deposition', '1: liquid; 2: sublimation', '1: solid; 2: deposition', '1: solid; 2: sublimation']": "1: solid; 2: sublimation"},

CodePudding user response:

If you write the dict out a little bit more clearly, you can see that this is a dict containing a dict, aka a nested dict.

{" Complete the following statement: changing state from ---(1)--- to gas is known as ---(2)---.": 
    {
        "['1: liquid; 2: evaporation', '1: liquid; 2: melting', '1: solid; 2: evaporation', '1: solid; 2: melting']": "1: liquid; 2: evaporation",
        "['1: liquid; 2: deposition', '1: liquid; 2: sublimation', '1: solid; 2: deposition', '1: solid; 2: sublimation']": "1: solid; 2: sublimation"
    }
}

To access the value you marked in bold, you would first have to access the nested dict within the top-level dict. You can do this via d['keyname'] or d.get('keyname').

d = {
    " Complete the following statement: changing state from ---(1)--- to gas is known as ---(2)---.": {
        "['1: liquid; 2: evaporation', '1: liquid; 2: melting', '1: solid; 2: evaporation', '1: solid; 2: melting']": "1: liquid; 2: evaporation",
        "['1: liquid; 2: deposition', '1: liquid; 2: sublimation', '1: solid; 2: deposition', '1: solid; 2: sublimation']": "1: solid; 2: sublimation"
    }
}

nested_d = d.get(" Complete the following statement: changing state from ---(1)--- to gas is known as ---(2)---.")
print(nested_d.get("['1: liquid; 2: evaporation', '1: liquid; 2: melting', '1: solid; 2: evaporation', '1: solid; 2: melting']"))
# output: "1: liquid; 2: evaporation"
  • Related