Python Dictionary - get method with example

Method Name:

get

Method Signature:

get(dict_key[,default_value])

Method Overview:

Returns the value associated with a key in the python dictionary object.

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:

# 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:

Liverpool
Arsenal
None

Example 2:

# 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:

Florida Cup

 


Copyright 2024 © pythontic.com