Example 1: print key of dictionary python
for key, value in mydic.items() :
print (key, value)
Example 2: printing python dictionary values
#print keys and values from the dictionary
for k, v in dic.items():
print(k, v)
Example 3: how to get the key for a value in a dictionary in python
# function to return key for any value
def get_key(val):
for key, value in my_dict.items():
if val == value:
return key
return "key doesn't exist"
# Driver Code
my_dict ={"java":100, "python":112, "c":11}
print(get_key(100))
print(get_key(11))
Example 4: how to print all elements of a dictionary in python
# you can also use items method
my_dict = {"one": 1,"two":2,"three":3,"four":4}
for key,value in my_dict.items():
print("Key : {} , Value : {}".format(key,value))
Example 5: python dictionary
#Creating dictionaries
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
#Creating new pairs and updating old ones
dict1['area'] = 25 #{'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter'] = 20 #{'color': 'red', 'edges': 4, 'perimeter': 20}
#Accessing values through keys
print(dict1['shape'])
#You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key') #returns None
dict1.get('false_key', "key not found") #returns the custom message that you wrote
#Deleting pairs
dict1.pop('volume')
#Merging two dictionaries
dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
dict1 #{'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}
#Getting only the values, keys or both (can be used in loops)
dict1.values() #dict_values(['red', 'square', 25, 4, 20])
dict1.keys() #dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items()
#dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])
Example 6: how to print all elements of a dictionary in python
my_dict = {"one": 1,"two":2,"three":3,"four":4}
for item in my_dict:
print("Key : {} , Value : {}".format(item,my_dict[item]))
# it will give this result >>> Key : One , value : 1
# Key : two , value : 2 ....