Skip to main content

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)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.