I have a dictionary of dictionaries, like given below:
{
"dev": {
"project_id": "dev_project_id",
"secret_id": "dev_secret_id",
"secret_project_id": "dev_secret_project_id",
"service_account_email": "[email protected]",
"email_list": ["[email protected]"],
"core_func_path":"dev/core_func.py",
"secret_id_email": "dev_secret_id_email"
},
"prod": {
"project_id": "prod_project_id",
"secret_id": "prod_secret_id",
"secret_project_id": "prod_secret_project_id",
"service_account_email": "[email protected]",
"email_list": ["[email protected]"],
"core_func_path":"prod/core_func.py",
"secret_id_email": "prod_secret_id_email"
}
}
And I need to extract key when a specific project_id is provided.
Till now, I have this code, which can get values from a dictionary, however, it is failing for a dictionary of dictionaries.
check_project_id='dev_project_id'
curr_dir = Path(os.path.dirname(os.path.abspath(__file__)))
default_config_dir = os.fspath(Path(curr_dir.parent.parent, 'config').resolve())
constants_path = str(default_config_dir) '/config.json'
with open(constants_path, 'r') as f:
std_config = json.load(f)
for val in std_config.values():
if(val['project_id']==check_project_id):
print(list(std_config.keys())[list(std_config.values()).index(check_project_id)])
Is there any way I can implement this?
CodePudding user response:
So if I understand correctly, std_config
is your dictionary of dictionaries. Just use the items
call on the dictionary to be able to extract the key that matches your criteria.
for k, v in std_config.items():
if v["project_id"] == check_project_id:
print(k)
> dev