how to get value of a key code example

Example 1: python dictionary get default

dictionary = {"message": "Hello, World!"}

data = dictionary.get("message", "")

print(data)  # Hello, World!

Example 2: python get value from dictionary

dict = {'color': 'blue', 'shape': 'square', 'perimeter':20}
dict.get('shape') #returns square

#You can also set a return value in case key doesn't exist (default is None)
dict.get('volume', 'The key was not found') #returns 'The key was not found'

Example 3: get key from a value

person = {'name': 'Phill', 'age': 22}

print('Name: ', person.get('Phill'))
print('Age: ', person.get('age'))

# value is not provided
print('Salary: ', person.get('salary'))

# value is provided
print('Salary: ', person.get('salary', 0.0))

Tags:

Misc Example