Python Dictionary - get method with example

Access the value corresponding to a key stored in a Python dictionary object with the get method of Python Dictionary

Dictionary Updated 10 Sep 2016 2 min read

Method Name

get

Method Signature

get(dict_key[,default_value])

Method Overview

  • Returns the value associated with a key in a Python dictionary object.
  • The get() method differs from dictionary lookup using the [] operator by not raising a KeyError when a given key is not found.
  • Also when using get() method to get the corresponding value for a given key, a default value can be specified which is returned when the key is not found.

Parameters

dict_key – The key for which the value needs to be found in the dictionary.

default_value – This is an optional parameter. If the default value is specified the value is returned when a key is not found in the dictionary object. If this parameter is not specified and the key is not found in the dictionary the get() method returns None.

Exception Handling

This method will not raise a KeyError when the specified key is not found in the dictionary. Refer to the default_value parameter above.

Example 1

python
# Example Python program that retrieves

            # the value associated with a key

            # of a dictionary

# Create a Python dictionary

            football_teams = dict()

# Populate the dictionary

            football_teams["A"] = "FC Barcelona"

            football_teams["B"] = "Real Madrid"

            football_teams["C"] = "Manchester United"

            football_teams["D"] = "Bayern Munich"

            football_teams["E"] = "Paris Saint-Germain"

            football_teams["F"] = "Manchester City"

            football_teams["G"] = "Liverpool"

            football_teams["H"] = "Tottenham Hotspur"

            football_teams["I"] = "Chelesa"

            football_teams["J"] = "Juventus"

# Retrieve the value corresponding to the

            # dictionary key "G"

            print(football_teams.get("G"))

            print(football_teams.get("P", "Arsenal"))

            print(football_teams.get("Q"))

Output

Output
Liverpool

            Arsenal

            None

Example 2

python
# Example Python program that accesses

            # the value corresponding to a given key

            # in a Python dictionary

            leagues = {1: "Arab Club Champions Cup",

                       2: "Club Friendlies",

                       3: "ConIFA World Football Cup",

                       4: "FIFA Club World Cup",

                       5: "Florida Cup",

                       6: "Friendlies",

                       7: "Intercontinental Cup",

                       8: "International Champions Cup",

                       9: "Kirin Cup",

                      10: "Olympics"}

print(leagues.get(5))

Output

Output
Florida Cup