Search code examples
pythonarraysdictionarydata-structureshardcode

Access dictionary with elements from array softcoded


I have a dictionary created from JSON. I would like to access items in the dictionairy through arrays containing their keys. Visualised JSON:

{
  "name": "Chiel",
  "industry": {
    "IndustryName": "Computer Science",
    "company": {
      "companyName": "Apple",
      "address": {
        "streetName": "Apple Park Way",
        "streetNumber": "1"
      }
    }
  },
  "hobby": {
    "hobbyName": "Music production",
    "genre": {
      "genreName": "Deep house",
      "genreYearOrigin": "1980"
    }
  }
}

See the following code example:

#create dict
jsonData = '{"name":"Chiel","industry":{"IndustryName":"Computer Science","company":{"companyName":"Apple","address":{"streetName":"Apple Park Way","streetNumber":"1"}}},"hobby":{"hobbyName":"Music production","genre":{"genreName":"Deep house","genreYearOrigin":"1980"}}}'
dictionary = json.loads(jsonData)

#Referencing dict for 'streetName', from array, hardcoded.    
companyElements = ["industry", "company", "address", "streetName"]
print(dictionary[companyElements[0]][companyElements[1]][companyElements[2]][companyElements[3]])

#Referencing dict for 'genreName', from array, hardcoded.    
hobbyElements = ["hobby", "genre", "genreName"]
print(dictionary[hobbyElements[0]][hobbyElements[1]][hobbyElements[2]])

The problem is that accessing the dictionaries is being done hardcoded. In other words, there are numbers being used (0, 1, 2, 3).

Is it possible to access the dictionairy through an array, but soft coded? So passing in an array (or another data structure) to the dict without making use of numbers? If so, how can one achieve this?


Solution

  • A possible solution is (from the example you provided):

    def get_element(dictionary, array):
       x = dictionary.copy()
       for i in array:
          x = x[i]
       return x
    
    companyElements = ["industry", "company", "address", "streetName"]
    hobbyElements = ["hobby", "genre", "genreName"]
    
    print(get_element(dictionary, companyElements))
    print(get_element(dictionary, hobbyElements))