How does the dictionary work in Python?

Key takeaways:

  • Dictionaries store data as key-value pairs.

  • Keys must be unique and immutable; values can be of any data type.

  • Elements can be accessed, added, updated, or deleted using specific syntax and methods.

  • Built-in methods like clear(), get(), items(), keys(), update(), and values() make working with dictionaries easier.

  • The len() function returns the number of key-value pairs in a dictionary.

  • The str() and type() functions allow you to convert a dictionary to a string and check its type, respectively.

In Python, a dictionary is a versatile data structure that allows you to store data as key-value pairs. Each key in a dictionary is unique and maps to a corresponding value. This structure enables fast lookups, making dictionaries ideal for scenarios where quick access to data is needed based on a specific key. Dictionaries are flexible, as the values can be of any data type, but the keys must be immutable types such as strings, numbers, or tuples. You can easily access, update, add, or delete elements within a dictionary using straightforward syntax and built-in methods.

A dictionary is a collection of keys and values. Every key corresponds to a single value. A key-value pair, often known as an item, is the relationship between a key and a value.

A colon (:) separates each key from its value, commas (,) divide key-value pairs, and curly braces ({}) encompass the entire document. Just two curly braces are used to write an empty dictionary with no elements, like in this example: ({}).

A dictionary in Python
A dictionary in Python

Values may not be unique within a dictionary, but keys are. A dictionary’s keys must be of an immutable data type (such as strings, numbers, or tuples), but its values can be of any kind.

Syntax

Here’s the syntax for how we can define dictionaries in Python:

dictionary = {key1: value1, key2: value2, key3: value3, ...}

Below is an example of a dictionary:

# example
dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
# All keys are unique:
# 'Name'
# 'Age'
# 'Class'

Accessing the dictionary

To access dictionary elements, you can use the familiar square brackets [], along with the key, to obtain its value.

dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
print(dict['Name'])

Note: If we attempt to access a key-value with a key that​ is not part of the dictionary, we get an error.

Insertion

Shown below is the method for adding new elements to a dictionary. We can also update existing elements:

dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
print(dict)
# Adding new key-value pair
dict['School'] = "GITAM"
print(dict)
# updating existing key-value pair
dict['Age'] = 8
print (dict)

Deletion

We have the option of clearing a dictionary’s full contents or only specific dictionary entries. In a single action, we may also remove the entire lexicon.

dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
print(dict)
# remove entry with key 'Name’
del dict['Name']
print(dict)
# remove all entries in dict
dict.clear()
print(dict)
# delete entire dictionary
del dict
print(dict)

Properties of dictionary keys

  1. It is not permitted to use duplicate keys. If a key already exists in a dictionary, its value is updated when attempting to add a new entry.

  2. Keys have to be unchangeable. This implies that tuples, strings, or numbers can be used as dictionary keys.

Dictionary functions

Below are some functions that dictionaries can be used with:

  • len(dict): Key-value pairs, or the total number of keys in a dictionary, are returned by the len() function. An illustration of how to utilize this function is provided below:

my_dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
print(len(my_dict)) # Output: 3
  • str(dict): The dictionary is transformed into a string representation that may be shown or written using the str() method. We can utilize it as follows:

my_dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
print(str(my_dict)) # Output: {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
  • type(variable): The type() function returns the type of the passed object. If the passed variable is a dictionary, it will return <class 'dict'>. Here’s how it can be used:

my_dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
print(type(my_dict)) # Output: <class 'dict'>
num = 5
print(type(num)) # Output: <class 'int'>

Dictionary built-in methods

Dictionaries in Python have some built-in methods that dictionaries can invoke. Shown below are some important ones:

  • dict.clear(): The dictionary is left empty once all of its contents are removed using the clear() method.

my_dict = {'Name': 'Sam', 'Age': 6, 'Class': 'First'}
my_dict.clear()
print(my_dict) # Output: {}
  • dict.get(key, default = None): If the value for the given key exists, it is returned by the get() method. It returns the default value (None if not given) if the key is not found.

my_dict = {'Name': 'Sam', 'Age': 6}
print(my_dict.get('Name')) # Output: 'Sam'
print(my_dict.get('Class', 'Not Available')) # Output: 'Not Available'
  • dict.items() : A view object displaying a list of dictionary key-value tuple pairs is returned by the items() method.

my_dict = {'Name': 'Sam', 'Age': 6}
print(my_dict.items()) # Output: dict_items([('Name', 'Sam'), ('Age', 6)])
  • dict.keys(): A view object displaying a list of all the dictionary’s keys is returned by the keys() method.

my_dict = {'Name': 'Sam', 'Age': 6}
print(my_dict.keys()) # Output: dict_keys(['Name', 'Age'])
  • dict.update(dict2): The key-value pairs from dict2 are combined into dict using the update() method. The new value from dict2 is added to the value of any existing keys.

dict1 = {'Name': 'Sam'}
dict2 = {'Age': 6}
dict1.update(dict2)
print(dict1) # Output: {'Name': 'Sam', 'Age': 6}
  • dict.values(): A view object containing a list of every value in the dictionary is returned by the values() method.

my_dict = {'Name': 'Sam', 'Age': 6}
print(my_dict.values()) # Output: dict_values(['Sam', 6])

Master the art of writing clean code with “Clean Code in Python.” From Python basics to advanced concepts like decorators and async programming, gain the skills to build efficient, maintainable applications.

Conclusion

Dictionaries in Python provide an efficient way to store and manage key-value pairs, offering fast data retrieval based on unique keys. They are highly flexible, allowing for easy access, modification, and deletion of elements. Understanding their properties and built-in methods enhances their usability in various scenarios, especially when quick lookups are needed.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How does a dictionary work internally?

Internally, a dictionary in Python uses a hash table where keys are hashed into indices to quickly locate and retrieve associated values.


What is the algorithm of a dictionary in Python?

The algorithm of a dictionary in Python involves hashing keys to store values in memory, allowing for fast lookup, insertion, and deletion based on the key.


What is the purpose of a dictionary?

The purpose of a dictionary is to store and retrieve data efficiently using unique keys that map to corresponding values.


How are dictionaries stored in memory in Python?

Dictionaries in Python are stored in memory using a hash table, where keys are hashed to determine their position, allowing for fast lookups.


Free Resources