Python get value from dict:

The Python get() method from dict returns the value for the given key if the key is present in the dictionary. In the absence of a key, this method returns the “None”. Hence, this method never raises a KeyError exception.

Method signature

The signature for the get() method is as shown below. In this case, k refers to the key whose value is to be extracted. Furthermore, the parameter default sets the default value in the absence of the key.

v=get(k,default)

Method parameters and return type

  • The get() method takes two parameters. Here, the first parameter is a key whose value is to be extracted. Furthermore. The second parameter default represents the default value to be displayed in the absence of key. However, this method will display none in the absence of a second parameter.
  • However, it returns the value of key given in the parameter.

Python Dictionary get Examples:

Example 1:

Let us take a dictionary with numbers assigned to color names in this example. Here, we will extract the value of key 1 and 11. As we can see, we could successfully extract the value of key 1 whereas for key 11, this prints none.

#Initializing 
color={1:"Red",2:"Blue",3:"Green"}
# Using get method
v1=color.get(1)
v2=color.get(11)
#Printing 
print("Value for key 1 is ",v1)
print("Value for key 11 is ",v2)

Output

Value for key 1 is  Red
Value for key 11 is  None

Example 2:

Let us take a dictionary with numbers assigned to a list containing names in this example. Furthermore, we provide the default value to display in the absence of a key. Now, when we extract the value of key 3 and 5, then it successfully extracts the value of 3 but not 5. As a result, it displays default value for the key 5.

#Initializing 
n={1:["Jim","Kim"],2:["John","Tom"],3:["Riya","Siya"]}
# Using get method
v1=n.get(3,"No students found")
v2=n.get(5,"No students found")
#Printing 
print("Value for key 3 is ",v1)
print("Value for key 5 is ",v2)

Output

Value for key 3 is  ['Riya', 'Siya']
Value for key 5 is  No students found

Example 3:

In this example, We will take a dictionary with the key and values as a tuple.

#Initializing 
n={"Comp":("Jim","Kim"),"IT":("John","Tom"),"EXTC":("Riya","Siya")}
# Using get method
v1=n.get("Comp","No students found")
v2=n.get("Electrical","No students found")
#Printing 
print("Students from Computer ",v1)
print("Students from Electrical ",v2)

Output

Students from Computer  ('Jim', 'Kim')
Students from Electrical  No students found

Conclusion

The get() method extracts the values mapping to a key in the dictionary. However, if the key is not present, this method returns None.

References

Happy Learning 🙂

Leave A Comment