Sam
Sam

Reputation: 641

Fastest way to handle nested dictionaries

I'm new to python and I'm trying to learn the best ways to write very fast code. I'm working on an exercise of handling nested dictionaries, and here is the dictionary that I'm working with:

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

Here is the code that I've written to access it. But because I have three nested for loops, I don't think this is as fast as it could be:

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)

Any pointers on how I can make my code both more concise and faster? Thanks a lot in advance!

Upvotes: 4

Views: 2635

Answers (2)

Hackaholic
Hackaholic

Reputation: 19771

you can create a function and return value:

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

And I can see in your code you want to access only date key. you can do like below:

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

This is fastest you can do. Because time complexity of accessing the value of dictionary is o(1).

Upvotes: 0

blhsing
blhsing

Reputation: 107134

A few points:

  1. The main_key variable from your main loop is unused, so you can simply iterate over dictionary.values() instead.
  2. The if main_value: statement is redundant because the following for loop won't iterate if main_value is empty anyway.
  3. The innermost loop over value.items() is unnecessary because all it's doing is to find the date key of the value dict and print its value, which you can accomplish by simply using square brackets to access the value dict by the date key. Put a try block around it to ignore a missing date key because that's how your current code behaves.

With the above points taken, your code should look like:

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

Upvotes: 4

Related Questions