1. python
  2. /basics
  3. /dictionaries

Python Dictionaries

In Python, a dictionary is a built-in data structure that is used to store key-value pairs. Dictionaries are also commonly referred to as "associative arrays" or "hash maps" in other programming languages. Dictionaries are mutable, which means that their elements can be changed after they are created.

A dictionary is created by placing a comma-separated list of key-value pairs inside curly braces {}. The keys and values in a dictionary can be of any type, and are separated by a colon. For example:

my_dict = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}

Dictionaries are unordered, which means that the elements are not stored in any particular order. This means that the elements of a dictionary cannot be accessed by indexing or slicing, as they can with lists or tuples. Instead, elements in a dictionary are accessed using the keys. For example:

print(my_dict['apple']) # 0.5

Dictionaries also support a number of built-in methods for adding, modifying, and deleting elements. For example, the update() method can be used to add multiple key-value pairs to a dictionary at once. The del statement can be used to delete a key-value pair from a dictionary, and the pop() method can be used to remove a key-value pair and return its value.

It is also possible to check if a key is present in a dictionary using the in keyword, or get the list of keys and values using keys() and values() methods respectively. The items() method returns a list of key-value pairs.

Dictionaries can commonly be used to implement data structures such as sets and queues. For example, a set can be implemented by using a dictionary with the keys as the set elements and the values as a placeholder.

Creating a Dictionary

In Python, a dictionary is created by placing a comma-separated list of key-value pairs inside curly braces {}. The keys and values in a dictionary can be of any type, and are separated by a colon.

There are several ways to create a dictionary in Python:

Using curly braces {}

You can create an empty dictionary using curly braces {} and add elements to it using the square brackets [] and the assignment operator (=).

# Creating an empty dictionary
my_dict = {}

# Adding elements to the dictionary
my_dict['apple'] = 0.5
my_dict['banana'] = 0.25
my_dict['orange'] = 0.75

Using the dict() constructor

You can create a dictionary using the dict() constructor and passing in key-value pairs as arguments.

# Creating a dictionary using the dict() constructor
my_dict = dict(apple=0.5, banana=0.25, orange=0.75)

Using a comprehension

You can create a dictionary using a dictionary comprehension, which allows you to create a dictionary using a concise syntax.

# Creating a dictionary using a comprehension
my_dict = {fruit: price for fruit, price in [('apple', 0.5), ('banana', 0.25), ('orange', 0.75)]}

In any of the above ways, the resulting dictionary will be the same: my_dict={'apple': 0.5, 'banana': 0.25, 'orange': 0.75}.

Accessing Dictionary Elements

In Python, elements within a dictionary can be accessed using the keys associated with them. The keys are used to look up the corresponding values in the dictionary.

To access an element in a dictionary, you use the square brackets [] and the key associated with the value you want to access. For example:

my_dict = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}
print(my_dict['apple']) # 0.5

You can also use the get() method to access the value of a key in a dictionary. This method returns the value of the key if it exists in the dictionary, otherwise it returns a default value, which is None by default.

print(my_dict.get('apple')) # 0.5
print(my_dict.get('mango')) # None

If you are not sure if a key is in the dictionary or not, you can use the in keyword to check if a key is present in the dictionary, before trying to access its value.

if 'apple' in my_dict:
    print(my_dict['apple'])
else:
    print("Key not found")

It is also possible to access all keys and values of a dictionary using the keys() and values() methods, respectively.

print(my_dict.keys()) # ['apple', 'banana', 'orange']
print(my_dict.values()) # [0.5, 0.25, 0.75]

And also use the items() method to get a list of key-value pairs.

print(my_dict.items()) # [('apple', 0.5), ('banana', 0.25), ('orange

Built-in Methods

Python dictionaries have a number of built-in methods that can be used to add, modify, and delete elements, as well as retrieve information about the dictionary. Some of the most commonly used built-in dictionary methods include:

clear()

This method removes all items from the dictionary.

my_dict.clear()

copy()

This method returns a shallow copy of the dictionary.

new_dict = my_dict.copy()

fromkeys(seq[, v])

This method creates a new dictionary with keys from a given sequence and value equal to v (defaults to None).

new_dict = dict.fromkeys(['apple', 'banana', 'orange'], 0)

get(key[, default])

This method returns the value of the key if it exists in the dictionary, otherwise it returns a default value. If no default value is provided, it returns None.

print(my_dict.get('apple'))

items()

This method returns a view object that displays a list of a given dictionary's (key, value) tuple pair.

print(my_dict.items())

keys()

This method returns a view object that displays a list of all the keys in the dictionary.

print(my_dict.keys())

pop(key[, default])

This method removes and returns an element with the specified key. If the key is not found, it returns a default value. If no default value is provided, it raises a KeyError.

print(my_dict.pop('apple'))

popitem()

This method removes and returns an arbitrary (key, value) pair from the dictionary. If the dictionary is empty, it raises a KeyError.

print(my_dict.popitem())

setdefault(key[, default])

This method returns the value of the key if it exists in the dictionary, otherwise it adds a key with a default value to the dictionary. If no default value is provided, it defaults to None.

print(my_dict.setdefault('apple', 0.5))

update([other])

This method updates the dictionary with key/value pairs from other, overwriting existing keys. It accepts an iterable of key-value pairs or another dictionary.

my_dict.update({'mango': 1.0, 'kiwi': 0.5})

values()

This method returns a view object that displays a list of all the values in the dictionary.

print(my_dict.values())