Python Dictionary

In this tutorial you will learn:

  • Python Dictionary
  • Adding elements to a Dictionary
  • Accessing elements of a Dictionary
  • Removing elements from a Dictionary

Python Dictionary

Dictionary is a resource that that lists words and their meaning. So Dictionary data type in Python follow a similar concept, they define a key and a value. They are declared using curly brackets. Dictionaries in Python are mutable it means the values in a dictionary can be changed and they are also indexed but unordered.

For example:

myDictionary1 = { "Language": "Python", "Type": "Book", "Time": 2}

Adding elements to a Dictionary

Adding elements to a Dictionary is very simple just assign the value to a key by passing it as index in a Dictionary using square brackets.

For example:
  1. myDictionary1["Testing"] = "Python"
  2. myDictionary1["Coding"] = "Easy"
  3. print("Output after adding elements")
  4. print(myDictionary1)
Accessing elements of a Dictionary

There are two ways of accessing elements of a dictionary. One is to use get function. We need to call the get function with the dictionary and pass the key to that function. Another way is by putting the key in square brackets along with the dictionary name

  1. print("Getting specific elements")
  2. print("Value of Language", myDictionary1.get("Language"))
  3. print("Value of Type", myDictionary1["Type"])
  4. print(myDictionary1)

Removing elements from a Dictionary

There are multiple methods of removing elements from a Dictionary. First one is the del method which deletes the element whose key is passed to the dictionary. Second one is to use the pop function which needs a key to remove the element.

  1. print("Output after removing elements")
  2. del myDictionary1["Time"]
  3. myDictionary1.pop("Language")
  4. print(myDictionary1)

Add new comment