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

A 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

More examples

my_dict = {'apple': 5, 'banana': 3, 'orange': 2}

# Using square brackets
apple_count = my_dict['apple']
print(apple_count)  # Output: 5

# Using get() method
banana_count = my_dict.get('banana')
print(banana_count)  # Output: 3

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 or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.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. Required fields are marked *