How to Create a Dictionary in Python

Reading Time: 2 Minutes
Publication date:

Today, I’ll discuss dictionaries, a data type in Python. I will explain how to work with dictionaries, perform operations on them, how they function, and about dictionary comprehensions.

Dictionaries in Python are unordered collections containing objects of various types, accessible by keys. They are sometimes referred to as associative arrays or hash tables.

To work with dictionaries, you first need to create one. There are several ways to do this. The first method is by using literals:

d = {}
print(d)
d = {'dict': 1, 'dictionary': 2}
print(d)

The second method is by using the dict function:

d = dict(short='dict', long='dictionary')
print(d)
d = dict([(1, 1), (2, 4)])
print(d)

The third method is by using the fromkeys method:

d = dict.fromkeys(['a', 'b'])
print(d)
d = dict.fromkeys(['a', 'b'], 100)
print(d)

The fourth method is using dictionary comprehensions, which are similar to list comprehensions:

d = {a: a ** 2 for a in range(7)}
print(d)

Now, let’s understand how to add entries to a dictionary and retrieve values by keys:

d = {1: 2, 2: 4, 3: 9}
print(d[1])
d[4] = 4 ** 2
print(d)
print(d.get('1'))  # Using get() to avoid exceptions for non-existent keys

As shown in the example, assigning a new key expands the dictionary, assigning an existing key changes its value, and attempting to retrieve a non-existent key raises an exception. To avoid the exception, you can use a special method (as shown above), or you can catch the exception.

What else can you do with dictionaries? You can do with them what you do with other objects: use built-in functions, keywords (like for and while loops), and methods specific to dictionaries.

Dictionary Methods

  • dict.clear() – Clears the dictionary.
  • dict.copy() – Returns a copy of the dictionary.
  • classmethod dict.fromkeys(seq[, value]) – Creates a dictionary with keys from seq and values set to value (default is None).
  • dict.get(key[, default]) – Returns the value of the key, but if the key does not exist, it returns default (default is None).
  • dict.items() – Returns dictionary’s key-value pairs.
  • dict.keys() – Returns dictionary’s keys.
  • dict.pop(key[, default]) – Removes the key and returns its value. If the key does not exist, it returns default (default raises an exception).
  • dict.popitem() – Removes and returns a (key, value) pair. Raises KeyError if the dictionary is empty.
  • dict.setdefault(key[, default]) – Returns the value of the key, but if it does not exist, it sets the key with the default value (default is None).
  • dict.update([other]) – Updates the dictionary with the key-value pairs from other, overwriting existing keys. Returns None.
  • dict.values() – Returns dictionary’s values.

These methods allow for flexible and efficient manipulation of dictionaries in Python.

5 / 5. 1

Share:

Leave a comment