Home > Software engineering >  How to get values inside a value by year using JSON?
How to get values inside a value by year using JSON?

Time:04-20

I am completely new to python and was hoping to use it to plot some values in a JSON file I was given.

The data looks like the following:

{
  "2015C": {
    "FIRSTDEPT": {
      "instructor quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    },
    "SECONDDEPT": {
      "instructor quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    }
  },
  "2016A": {
    "FIRSTDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    },
    "SECONDDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    }
  }
}

Is it possible to get, for example, just the "instructor_quality" ratings for FIRSTDEPT into a list of values with it corresponding to the year/time?

For example :

[(2015C, 4.0), (2016A, 4.0)]

So that I can eventually plot them (different ratings and enrollment numbers) by time? How would I go about getting those values using the keys I believe are present? Thank you so much!

CodePudding user response:

Something like this?

d = {
  "2015C": {
    "FIRSTDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    },
    "SECONDDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    }
  },
  "2016A": {
    "FIRSTDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    },
    "SECONDDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    }
  }
}

def foo(target_dict : dict, t1='FIRSTDEPT', t2='instructor_quality'):
    return [( key, target_dict[key][t1][t2] ) for key in target_dict ]

print( foo(d) ) # [('2015C', 4), ('2016A', 4)]

Although I did notice that you had two different keys, instructor_quality and instructor quality, I assumed that was a typo.

CodePudding user response:

something like this maybe?

data = {
  "2015C": {
    "FIRSTDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    },
    "SECONDDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    }
  },
  "2016A": {
    "FIRSTDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    },
    "SECONDDEPT": {
      "instructor_quality": 4,
      "course_quality": 4,
      "enrollments_sum": 30
    }
  }
}

years = data.keys()
result=[]
for year in years:
    result.append((int(year[:4]),data[year]["FIRSTDEPT"]["instructor_quality"]))
    
print(result)
  • Related