Python Dictionary

Python Dictionary

Dictionary is a collection of key:value pairs.

Python Dictionary

In a dictionary, keys are unique. Each key has an associated value. You can access value using key in a Dictionary.

Create a Dictionary

In Python, Dictionary can be created using curly brackets and comma separated key:value pairs.

Following is an example of initializing or creating a Python Dictionary with three key:value pairs.

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

Where myDictionary variable holds the dictionary. You can use this variable name to access the items of the dictionary or call dictionary related functions.

You can use print() function to print dictionary to console. Dictionary is converted to a String constant and then printed.

In the following program, we will create a dictionary and print the dictionary to console.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

print(myDictionary)
Run Code Copy

Output

{'name': 'Lini', 'year': 1989, 'expertise': 'data analytics'}

The dictionary is printed as a single string.

To know about printing dictionary key:value pairs, keys, or values, refer Python Print Dictionary.

Check if given Python object is a dictionary

You can check the type of the dictionary variable, if it is actually a dictionary. Use type() function as shown below. type() function returns the class type of variable.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

print(type(myDictionary))
Run Code Copy

Output

<class 'dict'>

<class 'dict'> means dictionary class. dict is shorthand for dictionary.

Loop through key:value pairs in given dictionary

Dictionary is a collection of items. You can loop through these items using a looping technique.

In this example, we will write a Python program to traverse through key:value pairs of a Dictionary using Python For Loop.

Python Program

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

for key, value in myDictionary.items():
	print(key, ': ', value)
Run Code Copy

Output

name :  Lini
year :  1989
expertise :  data analytics

Summary

In this tutorial of Python Examples, we learned how to create a Dictionary in Python, how to print a Dictionary to console, how to check if a Python object is a dictionary or not.

Related Tutorials

Code copied to clipboard successfully 👍