skip to Main Content

I have a dictionary that looks like the following:

{
"DICT_KEY1": {"nestKey1": "val", "nestKey2": "val", "nestKey3": "val"}
}

If I have a function that takes in a parameter like the dictionary above,
How would I access the key "DICT_KEY1" (not the values) without mentioning "DICT_KEY1" (since the nested dictionary passed into the parameter would be different each time)?

I can only think of accessing DICT_KEY1 by mentioning the key name, like:

dict1 = {(nested dictionary param)}
print(dict1['DICT_KEY1'])

2

Answers


  1. You can use list(dict.keys()) to access the keys as a list.

    For instance:

    d = {"DICT_KEY1": {"nestKey1": "val", "nestKey2": "val", "nestKey3": "val"}}
    print(list(d.keys()[0])
    

    This is fine for small dictionaries, but can be inefficient for large ones. If you have a bigger dictionary, using a library might be more appropriate. See this post for more guidance with third party libraries.

    Login or Signup to reply.
  2. The most efficient way to achieve that is using next() + iter() being the time complexity of this O(1).

    print(next(iter(dict1)))
    

    Transforming the keys of the dictionary into a list and accessing the first element will take O(n), what make that inneficient for bigger dictionaries.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search