xxxxxxxxxx
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'
xxxxxxxxxx
myDict = {
"message": "Hello Grepper!"
}
for key, value in myDict.items():
print(key) #Output: message
print(value) #Output: Hello Grepper!
xxxxxxxxxx
# define a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# get the values of the dictionary
values = my_dict.values()
# print the values
print(values) # dict_values([1, 2, 3])
# get a list of the values
values = list(my_dict.values())
# print the values
print(values) # [1, 2, 3]
xxxxxxxxxx
dict = {1: 'a', 2: 'b'}
value = 'a'
key = [x for x in dict.keys() if dict[x] == value][0]
xxxxxxxxxx
myDict = {
"comment": "A like if you love learning python with grepper!"
}
myDict["comment"] #retrieves comment if found. Otherwise triggers error
#or if not sure if key is in dictionary, avoid exiting code with error.
myDict.get("comment") #retrieves comment or None if not found in dict
xxxxxxxxxx
print(d.get('key5', 'NO KEY'))
# NO KEY
print(d.get('key5', 100))
# 100