d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}
keys = [k for k, v in d.items() if v == 'aaa']
print(keys)
# ['key1', 'key2']
keys = [k for k, v in d.items() if v == 'bbb']
print(keys)
# ['key3']
keys = [k for k, v in d.items() if v == 'xxx']
print(keys)
# []
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
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'
myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_items=myDict.items()
print("Given value is:")
myValue="PFB"
print(myValue)
print("Associated Key is:")
for key,value in dict_items:
if value==myValue:
print(key)