Last active
September 23, 2018 12:54
-
-
Save rameshrvr/cd9e1cdc1803918c7403b0cd103fc783 to your computer and use it in GitHub Desktop.
Get all keys of a nested dictionary python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from six import iteritems | |
def get_all_keys(dictionary): | |
""" | |
Method to get all keys from a nested dictionary as a List | |
Args: | |
dictionary: Nested dictionary | |
Returns: | |
List of keys in the dictionary | |
""" | |
result_list = [] | |
def recrusion(dictionary): | |
for key, value in iteritems(dictionary): | |
if isinstance(value, dict): | |
result_list.append(key) | |
recrusion(dictionary=value) | |
elif isinstance(value, list): | |
result_list.append(key) | |
for list_items in value: | |
recrusion(dictionary=list_items) | |
else: | |
result_list.append(key) | |
recrusion(dictionary=dictionary) | |
return result_list | |
details = { | |
"hardware_details": { | |
"model_name": "MacBook Pro", | |
"processor_details": { | |
"processor_name": "Intel Core i7", | |
"processor_speed": "2.7 GHz", | |
"core_details": { | |
"total_numberof_cores": "4", | |
"l2_cache(per_core)": "256 KB" | |
} | |
}, | |
"total_number_of_cores": "4", | |
"memory": "16 GB", | |
}, | |
"os_details": { | |
"product_version": "10.13.6", | |
"build_version": "17G65" | |
}, | |
"name": "Test", | |
"date": "YYYY-MM-DD HH:MM:SS" | |
} | |
print get_all_keys(dictionary=details) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment