Access dictionary values in Python | dict[key] vs dict.get(key)

Access dictionary values in Python | dict[key] vs dict.get(key)

dict[key] and dict.get(key) are two ways to access dictionary values in Python. The difference is that dict.get(key) takes two arguments while dict[key] takes one argument only.

In dict[key], if the key is missing in the dictionary then a KeyError is raised.

The second argument of dict.get(key) is the default value and is returned when the key is missing there in the dictionary. If the default is not given, it defaults to None, so that this method never raises a KeyError.

Example: dict[key] vs dict.get(key)

Code:

my_dict = {
  'key1':'value1',
  'key2':'value2',
  'key3':'value3',
  'key4':'value4'
}

print(my_dict)

print(my_dict.get('key1'))

print(my_dict['key1'])

print(my_dict.get('key5', 'some value'))

print(my_dict['key5'])

Output:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
value1
value1
some value

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    print(my_dict['key5'])
KeyError: 'key5'

Note: This default value of .get() method is returned only if the key is not present in the dictionary, if the key is there in the dictionary, then whatever the value is will be returned.

Implementing dict.get(key) with dict[key]

Code:

my_dict = {
  'key1':'value1',
  'key2':'value2',
  'key3':'value3',
  'key4':'value4'
}

try:
    value5 = my_dict["key5"]
except KeyError:
    value5 = "value5"
    
print(value5)

Output:

value5

Accessing dictionary keys using loop

Code:

my_dict = {
  'key1':'value1',
  'key2':'value2',
  'key3':'value3',
  'key4':'value4'
}

for key in my_dict:
  print(key)

Output:

key1
key2
key3
key4

Access dictionary values in Python using loop

Code:

my_dict = {
  'key1':'value1',
  'key2':'value2',
  'key3':'value3',
  'key4':'value4'
}

for key in my_dict:
  print(my_dict[key])

Output:

value1
value2
value3
value4

Click here to check the discussion on dict[key] vs dict.get(key) on StackOverflow.

Thank you for visiting our website.


Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you