Python Dictionaries

Dictionaries are unordered collections of key-value pairs. They are useful for storing data that is associated with unique keys, allowing for fast and efficient lookups.


Creating Dictionaries

You can create a dictionary by placing key-value pairs inside curly braces {}, separated by commas. Each key is followed by a colon and its associated value.

Tutorials dojo strip

Explanation of Code:

Dictionaries allow you to store and retrieve values using unique keys. Keys can be of immutable types such as strings and numbers, while values can be of any data type.




Accessing Dictionary Items

You can access items in a dictionary by using their keys.

Explanation of Code:

Use the key inside square brackets to get the corresponding value from the dictionary.




Modifying Dictionary Items

Dictionaries are mutable, meaning you can change their items after creation.

Explanation of Code:

You can modify the value associated with a key by assigning a new value to that key.




Adding and Removing Items

You can add new key-value pairs to a dictionary and remove existing ones.

  • To add a new item, assign a value to a new key.
  • To remove an item, use the del statement or the pop() method.




Dictionary Methods

Python provides several built-in methods for dictionary manipulation.

  • keys(): Returns a list of keys in the dictionary.
  • values(): Returns a list of values in the dictionary.
  • items(): Returns a list of key-value pairs in the dictionary.
  • get(): Returns the value for a key, or a default value if the key is not found.




Python Dictionaries Example Code

Explanation of Code:

This program creates a dictionary of student information and demonstrates accessing, modifying, adding, removing items, and using dictionary methods.




Python Labs

Tutorials dojo strip