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: myDictionary1["Testing"] = "Python" myDictionary1["Coding"] = "Easy" print("Output after adding elements") 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

print("Getting specific elements") print("Value of Language", myDictionary1.get("Language")) print("Value of Type", myDictionary1["Type"]) 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.

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

Add new comment