Chad Chad - 6 months ago 21
Python Question

Return parent dictionary if key value exists

If I have a file that contains these dictionaries:

bank = {
"88386180860608512" : {
"balance" : 100,
"name" : "Aehnon"
},
"88469127777243136" : {
"balance" : 100,
"name" : "Balanceofevil"
},
"89741285950246912" : {
"balance" : 3310,
"name" : "Sharky"
}
}


if this evaluates to True:

b = [subdict["Name"] for subdict in bank.values()]
if "Sharky" in b:
return True
else:
return False


How can I print the dictionary it belongs to, 89741285950246912?

Answer

Iterate items to get both key (89741285950246912) and value:

for account_no, account in bank.items():
    if account['name'] == 'Sharky':
        print(account_no)

prints:

89741285950246912