如何使用元组作为字典键集

时间:2019-06-11 09:01:56

标签: python dictionary tuples

我将JSON文件解析为字典,下面是JSON数据示例

 "environmental": {
      "temprature": {
           "test" : "temprature",
           "unit": "c", 

           "now": 12.65,
           "now_timestamp": "10-06-2019 08:02:18", 

           "min": "12.5", 
           "min_timestamp": "03-06-2019 07:40:02", 

           "max": "32.84", 
           "max_timestamp": "03-06-2019 04:30:03"
      }, 

我想知道是否有一种方法可以使用字符串或元组获取这些值之一

预期结果

logging.info(dictionary_page_data_file['environmental']['temprature']['now'])

我已经尝试过了

thistuple = ("environmental", "temprature", "now")
logging.info(dictionary_page_data_file[thistuple])

这必须足够动态以适应各种级别的字典

2 个答案:

答案 0 :(得分:0)

您可以使用键作为元组来临时字典:

data = {
 "environmental": {
      "temprature": {
           "test" : "temprature",
           "unit": "c",

           "now": 12.65,
           "now_timestamp": "10-06-2019 08:02:18",

           "min": "12.5",
           "min_timestamp": "03-06-2019 07:40:02",

           "max": "32.84",
           "max_timestamp": "03-06-2019 04:30:03"
      }
}}

def keys_values(d, current_key=()):
    for k, v in d.items():
        yield current_key + (k, ), v
        if isinstance(v, dict):
            yield from keys_values(v, current_key + (k, ))

transformed_dict = {k: v for k, v in keys_values(data)}

print(transformed_dict[("environmental", "temprature", "now")])
print(transformed_dict[("environmental", "temprature", "min")])
print(transformed_dict[("environmental", "temprature", "max")])

打印:

12.65
12.5
32.84

答案 1 :(得分:0)

您可以编写一个递归浏览字典的小函数,类似于注释中@tobias_k链接的答案:

dictionary_page_data_file = {
  "environmental": {
      "temprature": {
           "test" : "temprature",
           "unit": "c", 

           "now": 12.65,
           "now_timestamp": "10-06-2019 08:02:18", 

           "min": "12.5", 
           "min_timestamp": "03-06-2019 07:40:02", 

           "max": "32.84", 
           "max_timestamp": "03-06-2019 04:30:03"
      }}}

def get_keys(keys, d):
  if not keys:
    return d
  key = keys[0]
  return get_keys(keys[1:], d[key])

print(get_keys(('environmental', 'temprature', 'now'), dictionary_page_data_file))