Python Dictionary

In Python, a dictionary is a built-in data structure that is used to store and manipulate data in the form of key-value pairs. Each key in a dictionary must be unique and can be of any hashable data type such as a string, integer, or tuple. The values associated with each key can be of any data type, such as a string, integer, list, or another dictionary.

Here’s an example of how to create a dictionary in Python:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

In this example, we’ve created a dictionary called my_dict with three key-value pairs.

We can access the values in a dictionary by using their corresponding keys, like this:

print(my_dict['key1'])  # Output: 'value1'

We can also modify the values in a dictionary or add new key-value pairs:

my_dict['key1'] = 'new_value'
my_dict['key4'] = 'value4'

To remove a key-value pair from a dictionary, we can use the del keyword:

del my_dict['key1']

To iterate over the keys and values in a dictionary, we can use a for loop:

for key, value in my_dict.items():
    print(key, value)

This will output each key-value pair on a separate line.

Accessing the dictionary values:

In Python, you can access the values in a dictionary using their corresponding keys. There are a few different ways to access dictionary values:

  1. Using square brackets: You can access the value associated with a particular key using square brackets, like this:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_dict['key1'])  # Output: 'value1'
  1. Using the get() method: You can also use the get() method to access the value associated with a key. This method returns None if the key is not found in the dictionary (unless you specify a default value), which can be useful if you’re not sure whether a key exists in the dictionary.
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_dict.get('key2'))  # Output: 'value2'
print(my_dict.get('key4'))  # Output: None

You can also specify a default value to be returned if the key is not found:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_dict.get('key4', 'default_value'))  # Output: 'default_value'
  1. Using the values() method: If you just want to access all the values in a dictionary, you can use the values() method, which returns a list of all the values in the dictionary.
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_dict.values())  # Output: ['value1', 'value2', 'value3']
  1. Using the items() method: If you want to access both the keys and the values in a dictionary, you can use the items() method, which returns a list of tuples, where each tuple contains a key-value pair.
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_dict.items())  # Output: [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]

Deleting Elements using del Keyword:

In Python, you can delete elements from a dictionary using the del keyword. Here’s how to delete a key-value pair from a dictionary:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
del my_dict['key2']
print(my_dict)  # Output: {'key1': 'value1', 'key3': 'value3'}

In this example, we’ve deleted the key-value pair associated with the key 'key2'.

You can also delete all the elements in a dictionary using the clear() method:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
my_dict.clear()
print(my_dict)  # Output: {}

In this example, we’ve deleted all the key-value pairs in the my_dict dictionary.

Finally, you can delete the entire dictionary using the del keyword:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
del my_dict

In this example, we’ve deleted the entire my_dict dictionary. After running this code, if you try to access the my_dict variable, you’ll get a NameError because the variable no longer exists.

Deleting Elements using pop() Method:

In Python, you can also delete elements from a dictionary using the pop() method. This method removes the key-value pair associated with a given key and returns the corresponding value. Here’s how to use the pop() method:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
deleted_value = my_dict.pop('key2')
print(my_dict)  # Output: {'key1': 'value1', 'key3': 'value3'}
print(deleted_value)  # Output: 'value2'

In this example, we’ve deleted the key-value pair associated with the key 'key2' using the pop() method. The pop() method has removed the key-value pair from the dictionary and returned the corresponding value, which we’ve stored in the deleted_value variable.

If the key you specify is not found in the dictionary, the pop() method raises a KeyError. However, you can provide a default value to be returned if the key is not found, by passing the default value as a second argument to the pop() method:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
deleted_value = my_dict.pop('key4', 'default_value')
print(deleted_value)  # Output: 'default_value'

In this example, since the key 'key4' is not found in the dictionary, the pop() method returns the default value 'default_value'.

Iterating Dictionary:

In Python, you can iterate over the keys, values, or key-value pairs in a dictionary using various methods.

  1. Iterating over keys: To iterate over the keys in a dictionary, you can use a for loop:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for key in my_dict:
    print(key)

This will output:

key1
key2
key3
  1. Iterating over values: To iterate over the values in a dictionary, you can use the values() method:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for value in my_dict.values():
    print(value)

This will output:

value1
value2
value3
  1. Iterating over key-value pairs: To iterate over the key-value pairs in a dictionary, you can use the items() method:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for key, value in my_dict.items():
    print(key, value)

This will output:

key1 value1
key2 value2
key3 value3

In the for loop, we’re using two variables (key and value) to unpack each key-value pair in the dictionary. Inside the loop, we can use these variables to access the key and value of each pair.

You can also use the enumerate() function to iterate over a dictionary and get the index of each key-value pair:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for i, (key, value) in enumerate(my_dict.items()):
    print(i, key, value)

This will output:

0 key1 value1
1 key2 value2
2 key3 value3

In this example, we’re using the enumerate() function to get the index of each key-value pair in the dictionary, and then using two variables (key and value) to unpack each pair.

Properties of Dictionary Keys:

In Python, dictionary keys have the following properties:

  1. Uniqueness: Each key in a dictionary must be unique. If you try to add a key that already exists, the new value will overwrite the old value associated with the key.
  2. Immutable: Dictionary keys must be immutable objects. This means that you cannot use mutable objects such as lists as keys. However, you can use immutable objects such as strings, numbers, or tuples.

For example, you can use strings as keys:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

You can also use numbers as keys:

my_dict = {1: 'value1', 2: 'value2', 3: 'value3'}

And you can use tuples as keys, as long as the elements in the tuple are immutable:

my_dict = {('key1', 1): 'value1', ('key2', 2): 'value2'}

However, you cannot use lists as keys:

my_dict = {['key1', 1]: 'value1'}  # TypeError: unhashable type: 'list'
  1. Order: In Python 3.7 and later, dictionaries are guaranteed to maintain the insertion order of their keys. This means that if you add keys to a dictionary in a specific order, they will be stored in that order.

For example:

my_dict = {}
my_dict['a'] = 1
my_dict['b'] = 2
my_dict['c'] = 3
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

In this example, the keys are added to the dictionary in the order 'a', 'b', 'c', and the dictionary maintains this order.

However, in Python versions prior to 3.7, dictionaries do not maintain order. If you need to maintain order in older versions of Python, you can use the collections.OrderedDict class instead of a regular dictionary.

Built-in Dictionary Functions:

Python provides several built-in functions for working with dictionaries:

  1. len(): Returns the number of items (key-value pairs) in a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(len(my_dict))  # Output: 3
  1. str(): Returns a string representation of a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(str(my_dict))  # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
  1. type(): Returns the type of a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(type(my_dict))  # Output: <class 'dict'>
  1. dict(): Creates a new dictionary.

Example:

my_dict = dict(key1='value1', key2='value2', key3='value3')
print(my_dict)  # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
  1. sorted(): Returns a sorted list of keys in a dictionary.

Example:

my_dict = {'key1': 'value1', 'key3': 'value3', 'key2': 'value2'}
sorted_keys = sorted(my_dict)
print(sorted_keys)  # Output: ['key1', 'key2', 'key3']
  1. keys(): Returns a view object of the keys in a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
keys_view = my_dict.keys()
print(keys_view)  # Output: dict_keys(['key1', 'key2', 'key3'])
  1. values(): Returns a view object of the values in a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
values_view = my_dict.values()
print(values_view)  # Output: dict_values(['value1', 'value2', 'value3'])
  1. items(): Returns a view object of the key-value pairs in a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
items_view = my_dict.items()
print(items_view)  # Output: dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

View objects are dynamic and reflect changes made to the dictionary. So if you modify the dictionary, the view objects will also be updated.

Built-in Dictionary methods:

In addition to built-in functions, Python also provides several built-in methods for working with dictionaries:

  1. clear(): Removes all key-value pairs from a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
my_dict.clear()
print(my_dict)  # Output: {}
  1. copy(): Returns a shallow copy of a dictionary.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
copy_dict = my_dict.copy()
print(copy_dict)  # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
  1. get(): Returns the value associated with a specified key. If the key does not exist in the dictionary, it returns a default value (which is None by default, but can be specified).

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
value = my_dict.get('key2')
print(value)  # Output: 'value2'

value = my_dict.get('key4')
print(value)  # Output: None

value = my_dict.get('key4', 'default_value')
print(value)  # Output: 'default_value'
  1. pop(): Removes and returns the value associated with a specified key.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
value = my_dict.pop('key2')
print(value)  # Output: 'value2'
print(my_dict)  # Output: {'key1': 'value1', 'key3': 'value3'}
  1. popitem(): Removes and returns the last inserted key-value pair in a dictionary. This method is useful when you need to remove items from a dictionary in LIFO (last-in, first-out) order.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
item = my_dict.popitem()
print(item)  # Output: ('key3', 'value3')
print(my_dict)  # Output: {'key1': 'value1', 'key2': 'value2'}
  1. update(): Updates a dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2'}
new_dict = {'key3': 'value3', 'key4': 'value4'}
my_dict.update(new_dict)
print(my_dict)  # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}

my_dict.update(key3='new_value3')
print(my_dict)  # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'new_value3', 'key4': 'value4'}
  1. setdefault(): Returns the value associated with a specified key. If the key does not exist in the dictionary, it adds the key with a default value (which is None by default, but can be specified) and returns the default value.

Example:

my_dict = {'key1': 'value1', 'key2': 'value2'}
value