[英]I have a dictionary {string and int}. How do I compare integers values and not the keys within the same dictionary(python)
[英]In Python how would I compare 2 values in one dictionary that have the same values in another dictionary?
adict = {"a":(1,2),"b":(3,4),"c":(5,6),"d":(7,8)}
bdict = {"ax":(1,2),"xb":(3,4),"xc":(5,98),"xd":(7,99)}
我將如何在 bdict 中獲取密鑰。 我希望能夠檢查是否可以在 bdict 中找到 adict 中的值,如果它們確實存在,我可以獲取密鑰。 所以 output 將是“ax”和“xb”,因為在 adict 中,鍵“a”的兩個值都在 bdict 中。 與 adict (3,4) 中的 b 值相同
for k, v in bdict.items():
if v in adict.values():
print(k)
就像迭代bdict
並檢查值是否存在於adict.values()
一樣簡單。
或者:
res = [k for k, v in bdict.items() if v in adict.values()]
print(res)
印刷:
['ax', 'xb']
以下代碼返回 bdict 中其值出現在 adict 中的每個鍵的列表,它通過使用列表推導創建其值出現在 adict.values() 中的每個鍵的列表(這是所有 adict 值):
matched_values_keys = [bdict_key for bdict_key, bdict_value in bdict.items() if bdict_value in adict.values()]
希望有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.