Dictionaries
Introduction:
Dictionaries are a fundamental data structure in Python, providing a flexible and efficient way to store and retrieve data. Unlike sequences such as lists or tuples, dictionaries are unordered collections of items, where each item consists of a key-value pair. In this blog, we'll dive into the world of dictionaries in Python, exploring their syntax, operations, and practical use cases.
Sections
- What are Dictionaries?
- Why Use Dictionaries?
- What are the Characteristics of dictionaries
- Understanding Dictionaries:
- Creating a dictionary
- Common Dictionary Operations
- Conclusion
Section 1- What are Dictionaries?
Def: Programming languages all come with a variety of data structures, each suited to specific kinds of jobs. Among the data structures built into Python, the dictionary, or Python dict, stands out. Python dictionaries consists of one or more keys—an object like a string or an integer. Each key is associated with a value, which can be any Python object.
Def: A Python dictionary is a data structure that allows us to easily write very efficient code. In many other languages, this data structure is called a hash table because its keys are hashable.
Def: A Python dictionary is a collection of key: value pairs. You can think about them as words and their meaning in an ordinary dictionary. Values are said to be mapped to keys. For example, in a physical dictionary, the definition of science that searches for patterns in complex data using computer methods is mapped to the key Data Science.
Def: A dictionary is a data type similar to arrays but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.
Section 2- Why Use Dictionaries?
- A Python dictionary is a fast, versatile way to store and retrieve data by way of a name or even a more complex object type, rather than just an index number.
- You use a key to obtain its related values, and the lookup time for each key/value pair is highly constant.
- Python dictionaries allow us to associate a value to a unique key, and then to quickly access this value. It's a good idea to use them whenever we want to find (lookup for) a certain Python object. We can also use lists for this scope, but they are much slower than dictionaries.
- This speed is due to the fact that dictionary keys are hashable. Every immutable object in Python is hashable, so we can pass it to the hash() function, which will return the hash value of this object. These values are then used to lookup for a value associated with its unique key.
Section 3- What are the Characteristics of dictionaries
- Unordered (In Python 3.6 and lower version): The items in dictionaries are stored without any index value, which is typically a range of numbers. They are stored as Key-Value pairs, and the keys are their index, which will not be in any sequence.
- Ordered (In Python 3.7 and higher version): dictionaries are ordered, which means that the items have a defined order, and that order will not change. A simple Hash Table consists of key-value pair arranged in pseudo-random order based on the calculations from Hash Function.
- Unique: As mentioned above, each value has a Key; the Keys in Dictionaries should be unique. If we store any value with a Key that already exists, then the most recent value will replace the old value.
- Mutable: The dictionaries are changeable collections, which implies that we can add or remove items after the creation.
Section 2- Understanding Dictionaries:
A dictionary in Python is defined using curly braces {}, and items are separated by commas. Each item consists of a key and a corresponding value, linked together with a colon (:). Here's a simple example:For example, a database of phone numbers could be stored using a dictionary like this:
# Creating a dictionary
my_dict = {"name": "John", "age": 25, "city": "New York"}
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } print(phonebook)
{'John': 938477566, 'Jack': 938377264, 'Jill': 947662781}
Section 4- Creating a dictionary
There are following three ways to create a dictionary.
- Using curly brackets: The dictionaries are created by enclosing the comma-separated Key: Value pairs inside the {} curly brackets. The colon ‘:‘ is used to separate the key and value in a pair.
- Using dict() constructor: Create a dictionary by passing the comma-separated key: value pairs inside the dict().
- Using sequence having each item as a pair (key-value)
# create a dictionary using {}
person = {"name": "Jessa", "country": "USA", "telephone": 1178}
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}
# create a dictionary using dict()
person = dict({"name": "Jessa", "country": "USA", "telephone": 1178})
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}
# create a dictionary from sequence having each item as a pair
person = dict([("name", "Mark"), ("country", "USA"), ("telephone", 1178)])
print(person)
# create dictionary with mixed keys keys
# first key is string and second is an integer
sample_dict = {"name": "Jessa", 10: "Mobile"}
print(sample_dict)
# output {'name': 'Jessa', 10: 'Mobile'
Section: Common Dictionary Operations:
Adding Items:
my_dict["gender"] = "Male"
Iterating over dictionaries
Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:
phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
Removing a value
To remove a specified index, use either one of the following notations:
phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } del phonebook["John"] print(phonebook)
Checking if a Key Exists:
if "age" in my_dict:
print("Age is present.")
Conclusion:
Dictionaries in Python are a versatile and powerful tool for handling data. Their simplicity and efficiency make them essential for a wide range of programming tasks. Whether you're a beginner or an experienced developer, understanding how to leverage dictionaries will undoubtedly enhance your Python programming skills. So, the next time you need to organize and retrieve data efficiently, think dictionaries!