Python Dictionary

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Python tutorial, let us see Python Dictionary with an appropriate example program.

Introduction of Python Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values.

Code to Create and print a dictionary

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Accessing the items

We can access the dictionary items by referring to its key name, inside square brackets.

Example

Get the value of the “model” key from the above-said dictionary.

x = thisdict["model"]

Output

Mustang

The get() method is also used to get the same result.

Dictionary Length

We can determine the items present in the dictionary using the len() method.

Code to print the number of items in the dictionary

print(len(thisdict))

Output

3

Adding Items

Adding an item to the dictionary is performed by using a new index key and assigning a value to it.

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Output

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Removing Items

pop(), popitem(), del, clear() are some of the major methods to remove an item from the dictionary.

Program to remove an item using pop() method

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

Output

{'brand': 'Ford', 'year': 1964}

dict() Constructor

The dict() constructor is used to make a new dictionary.

Example 

thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Output

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Leave a Comment

Your email address will not be published. Required fields are marked *