Python – Check if key exists in dictionary

In Python, you can use the in operator to check if a key exists in a dictionary.

test.py

def main():
    fruits = {
        'apple':1,
        'orange':2,
        'banana':3
    }

    #if key 'apple' exists in fruits?
    if 'apple' in fruits:
        print(fruits['apple'])

if __name__ == '__main__':
    main()

Output

1

P.S Tested with Python 3.4.3
Note
has_key() is deprecated in favor of key in d.

發佈了1 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章