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
You can use
list(dict.keys())
to access the keys as a list.For instance:
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.
The most efficient way to achieve that is using next() + iter() being the time complexity of this O(1).
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.