【问题标题】:Fastest way to handle nested dictionaries处理嵌套字典的最快方法
【发布时间】:2018-11-07 04:36:55
【问题描述】:

我是 python 新手,我正在尝试学习编写非常快速的代码的最佳方法。我正在处理嵌套字典的练习,这是我正在使用的字典:

{
    "key_1": [
        {
            "title": <title>,
            "date": <date>,
            "text": <text>
        }
    ],
    "key_2": [
        {
             "title": <title>,
            "date": <date>,
            "text": <text>
        }
     ],
    "key_3": [
            {
                 "title": <title>,
                "date": <date>,
                "text": <text>
            }
     ]
}

这是我为访问它而编写的代码。但是因为我有三个嵌套的 for 循环,所以我认为这并没有那么快:

for main_key, main_value in dictionary.items():
    if main_value:
        for value in main_value:
            for sub_keys, sub_values in value.items():
                if sub_keys == "date":
                   print(sub_values)

关于如何使我的代码更简洁和更快的任何指示?提前非常感谢!

【问题讨论】:

标签: python python-3.x performance dictionary coding-efficiency


【解决方案1】:

几点:

  1. 主循环中的 main_key 变量未使用,因此您可以简单地迭代 dictionary.values()
  2. if main_value: 语句是多余的,因为如果main_value 为空,则以下for 循环将不会迭代。
  3. value.items() 上的最内层循环是不必要的,因为它所做的只是找到 value dict 的 date 键并打印其值,只需使用方括号访问 value 即可完成由date 键控制。在其周围放置一个 try 块以忽略缺少的 date 键,因为这就是您当前代码的行为方式。

考虑到以上几点,您的代码应如下所示:

for main_value in dictionary.values():
    for value in main_value:
        try:
            print(value['date'])
        except KeyError:
            pass

【讨论】:

    【解决方案2】:

    你可以创建一个函数并返回值:

    >>> def get_value(key1, key2=None):
    ...     if key1 and key2:
    ...         try:
    ...             return my_dict.get(key1).get(key2)
    ...         except Exception as e:
    ...             print(e)
    ...             return None
    ...     else:
    ...         return my_dict(key1)
    

    我可以在您的代码中看到您只想访问date 键。你可以像下面这样:

    >>> for x in my_dict:
    ...     print(my_dict[x].get('date'))
    

    这是您能做到的最快速度。因为访问字典值的时间复杂度是o(1)。

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2010-11-19
      • 2020-06-01
      • 2021-12-10
      • 2020-11-25
      相关资源
      最近更新 更多