Python dictionaries are a versatile and powerful data structure that allow you to store and retrieve key-value pairs. They are mutable, unordered, and can store any data type as a value. In this blog, we will explore the basics of Python dictionaries, their syntax, examples, and methods.

Creating a Dictionary

        You can create a dictionary in Python by enclosing a comma-separated list of key-value pairs in curly braces {}. Here's an example:
  person = {"name": "John", "age": 30, "city": "New York"}
  
In this example, we have a dictionary called person with three key-value pairs. The keys are strings ("name", "age", and "city"), and the values are a string, an integer, and another string.

Accessing Values in a Dictionary

        You can access the values in a dictionary using the key. Here's an example:
print(person["name"])

    This will output "John", which is the value associated with the key "name".

        If you try to access a key that does not exist in the dictionary, you will get a KeyError. To avoid this, you can use the get() method, which returns None if the key does not exist:
print(person.get("address"))

    This will output None.

Changing Values in a Dictionary

        You can change the value of a key in a dictionary by referencing the key and assigning a new value. Here's an example:
person["age"] = 35

    This will change the value associated with the key "age" from 30 to 35.

Adding and Removing Items in a Dictionary

        You can add a new key-value pair to a dictionary by assigning a value to a new key:

person["gender"] = "Male"

    This will add a new key-value pair to the person dictionary.

    You can remove an item from a dictionary using the pop() method, which removes the item with the specified key and returns its value:
person.pop("city")

This will remove the key-value pair with the key "city" from the person dictionary and return its value ("New York").

Dictionary Methods with examples

        Python dictionaries have several useful methods that you can use to manipulate the data. Here are some of the most common methods:
  • keys(): Returns a list of all the keys in the dictionary.
  • values(): Returns a list of all the values in the dictionary.
  • items(): Returns a list of all the key-value pairs in the dictionary as tuples.
  • clear(): Removes all the items from the dictionary.
  • copy(): Returns a shallow copy of the dictionary.
  • update(): Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.
Here's an example of using some of these methods:
person = {"name": "John", "age": 30, "city": "New York"}

print(person.keys())  # output: ["name", "age", "city"]
print(person.values())  # output: ["John", 30, "New York"]
print(person.items())  # output: [("name", "John"), ("age", 30), ("city", "New York")]

person.clear()
print(person)  # output: {}

person = {"name": "John", "age": 30, "city": "New York"}
person2 = {"gender": "Male"}

person.update(person2)
print(person)  # output: {"name": "John", "age": 30, "city": "New York", "gender": "Male"}
  

Here are some more methods that can be used with Python dictionaries:

  1. .get(key, default=None) - This method returns the value for the given key if it exists in the dictionary. If it doesn't, it returns the default value (which can be set to any value, but defaults to None).
  2. .pop(key, default=None) - This method removes and returns the value for the given key if it exists in the dictionary. If it doesn't, it returns the default value (which can be set to any value, but defaults to None).
  3. .popitem() - This method removes and returns an arbitrary (key, value) pair from the dictionary.
  4. .clear() - This method removes all (key, value) pairs from the dictionary.
  5. .update(other) - This method updates the dictionary with the (key, value) pairs from another dictionary or an iterable of (key, value) pairs.
  6. .keys() - This method returns a view object that contains the keys of the dictionary.
  7. .values() - This method returns a view object that contains the values of the dictionary.
  8. .items() - This method returns a view object that contains the (key, value) pairs of the dictionary.
  9. .copy() - This method returns a shallow copy of the dictionary.
  10. .fromkeys(seq, value=None) - This method creates a new dictionary with keys from the given sequence and values set to the given value. If no value is provided, the values are set to None.

Read Next Chapter Click Here ->  Type conversion and casting