A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas.
Here, we are creating a dictionary with integer keys and printing the dictionary, it’s keys, it’s values and key-value pairs.
- Printing the dictionary – To print a dictionary, just pass the dictionary_name in the print function.
Syntax:
print(dictionary_name)
- Printing the keys – To print the dictionary keys only, loop through the dictionary and print it, when we loop through a dictionary it returns the keys.
Syntax:
for key in dictionary_name:
print(key)
- Printing the values – To print the dictionary values only, loop through the dictionary and use the values() method, it returns the dictionary values.
Syntax:
for value in dictionary_name.values():
print(value)
- Print the key-value pairs – To print the keys & values both, loop through the dictionary and use the items() method, it returns the key-value pair.
Syntax:
for key,value in dictionary_name.items():
print(key, value)
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer