Skip to content

Get value by key dictionary Python | Example code

  • by

Simple use square bracket [] with a key on dictionary object to Get value by key dictionary Python.

dict[key]

Note: KeyError occurs if the key does not exist.

Or Use gets () method of the dictionary object dict to get any default value without raising an error if the key does not exist.

dict.get()

Example get value by key dictionary Python

Simple example code gets the dictionary value by specifying the key with dict[key].

d = {'key1': 100, 'key2': 200, 'key3': 300}

res = d['key1']

print(res)

Output:

Get value by key dictionary Python

Using dict.get() method

d = {'key1': 100, 'key2': 200, 'key3': 300}

res = d.get('key12')

print(res)

Output: None

Built-in Types dict.get() — Python 3.9.1 documentation, In both methods, The original dictionary itself does not change.

Do comment if you have any doubts and suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.