使用软编码数组中的元素访问字典

Access dictionary with elements from array softcoded

我有一本从 JSON 创建的字典。我想通过包含键的数组访问字典中的项目。可视化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"
    }
  }
}

参见下面的代码示例:

#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]])

问题是访问字典是硬编码的。换句话说,使用了数字 (0, 1, 2, 3)。

是否可以通过数组访问词典,但是是软编码的?那么在不使用数字的情况下将数组(或其他数据结构)传递给字典?如果是这样,如何才能做到这一点?

一个可能的解决方案是(根据您提供的示例):

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))

您可以编写一个迭代给定键的函数。

请注意,如果您的 JSON 中缺少一个或多个键,以下实现将不会捕获异常:

import json
import copy
#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"]

#Referencing dict for 'genreName', from array, hardcoded.
hobbyElements = ["hobby", "genre", "genreName"]

def get_dict_value(data, keys):
    result = copy.deepcopy(data)
    for key in keys:
        result = result[key]
    return result

print( get_dict_value(dictionary, companyElements) )
print( get_dict_value(dictionary, hobbyElements) )

结果:

Apple Park Way
Deep house

您可以使用 pandas 库。它在 Python 中非常有效地处理文件操作,因为它是用 C 编写的。 您可以使用 Pandas 中的 json_normalize 函数来完成此任务。

参考 - https://www.kaggle.com/jboysen/quick-tutorial-flatten-nested-json-in-pandas

import json
file=open('kk.json')
inp=json.load(file)
print(json_normalize(inp))