【问题标题】:How to use a tuple as dictionary key set如何使用元组作为字典键集
【发布时间】:2019-10-25 15:53:21
【问题描述】:

我将一个 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])

这必须足够动态以适应不同级别的字典

【问题讨论】:

标签: python dictionary tuples


【解决方案1】:

你可以写一个递归遍历字典的小函数,类似于cmets中@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))

【讨论】:

  • 非常感谢,不知道这到底是如何工作的,但看起来简单干净:-)
  • 一个问题,为什么要返回 get_keys(keys[1:], d[key]) 而不仅仅是 get_keys(keys[1:], d[key])
  • @WernerVenter 你的意思是没有回报?然后该函数将永远不会返回任何结果。由于它也不会就地修改数据,因此不会发生任何事情。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2010-11-28
    • 2019-02-12
    • 2011-12-25
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2014-01-28
    相关资源
    最近更新 更多