[英]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: 如果此计算结果为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? 如何打印它所属的字典,89741285950246912?
Iterate items to get both key
(89741285950246912) and value
: 迭代项目以获得两个key
(89741285950246912)和value
:
for account_no, account in bank.items():
if account['name'] == 'Sharky':
print(account_no)
prints: 打印:
89741285950246912
You can use a list comprehensions which returns a list of keys. 您可以使用列表推导来返回键列表。
>>> 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.