如果键值存在,则返回父词典

时间:2016-05-17 03:49:06

标签: python python-3.x dictionary

如果我有一个包含这些词典的文件:

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

如果评估为True:

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

如何打印它所属的字典,89741285950246912?

2 个答案:

答案 0 :(得分:2)

Iterate items同时获取key(89741285950246912)和value

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

打印:

89741285950246912

答案 1 :(得分:1)

您可以使用列表推导来返回键列表。

>>> bank = {
...     "88386180860608512" : {
...         "balance" : 100,
...         "name" : "Aehnon"
...     },
...     "88469127777243136" : {
...         "balance" : 100,
...         "name" : "Balanceofevil"
...     },
...     "89741285950246912" : {
...         "balance" : 3310,
...         "name" : "Sharky"
...     }
... }
>>> [key for key, value in bank.items() if value['name'] == 'Sharky']
['89741285950246912']