Internally, a dictionary in Python uses a hash table where keys are hashed into indices to quickly locate and retrieve associated values.
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(), andvalues()make working with dictionaries easier.The
len()function returns the number of key-value pairs in a dictionary.The
str()andtype()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: ({}).
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:
# exampledict = {'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 pairdict['School'] = "GITAM"print(dict)# updating existing key-value pairdict['Age'] = 8print (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 dictdict.clear()print(dict)# delete entire dictionarydel dictprint(dict)
Properties of dictionary keys
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.
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 thelen()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 thestr()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): Thetype()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 = 5print(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 theclear()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 theget()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 theitems()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 thekeys()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 intodictusing theupdate()method. The new value fromdict2is 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 thevalues()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