Dictionaries in python

One essential data type for storing data collections is a Python dictionary, sometimes referred to as a dict. They offer an adaptable method of data organisation by linking values to distinct keys. Dictionaries may be known as hashes, hashmaps, or associative arrays in various programming languages.
Dictionary Basics
Key-value pairs are used in dictionaries to store and retrieve data, as opposed to sequences like lists or tuples, which are indexed by their position. Every key corresponds to a certain value. To access the appropriate value, you utilise the key.
Since dictionaries can be altered after they are created, they are changeable. Although the specifics of Python’s implementation have evolved over time, the elements in a dictionary are typically regarded as unordered.
Making a Dictionary
Creating a Dictionary:
Using curly braces {} with key value pairs: Curly braces {} are frequently used to define dictionary literals with key:value pairs. {key1: value1, key2: value2,…} is the syntax. Each key and its value are separated by a colon (:), and the pairs are separated by commas (,).
Creating an empty dictionary: Either {} or the dictionary() function can be used to generate an empty dictionary.
Using the dictionary() constructor: There are multiple ways to generate dictionaries using the built-in dictionary() function
- Using keyword arguments (where keys are strings) from a series of key-value pairs (such as a list of tuples).
- Getting at Dictionary Values
Accessing Dictionary Values:
- Employing [key] square brackets: After the dictionary name, insert the key inside square brackets.
- A KeyError will be raised if you attempt to use square brackets to access a key that is not in the dictionary.
- Using the get() method This approach offers a more secure means of obtaining values. dictionary.The value for the given key is returned by get(key). It returns None by default if the key cannot be located, or a given default value if the second argument is supplied. By doing this, the KeyError that [] access would cause is avoided.
Operators and Built-in Functions/Methods:
For working with dictionaries, Python has a number of operators and built-in functions and methods
- The number of key-value pairs (items) in the dictionary is returned by the len() function.
- In and not in: A method of determining whether a key is present in the dictionary.
- Comparison (==,!=): Verifies whether two dictionaries contain identical key-value pairs. Equality is unaffected by ordering. Dictionaries are not compatible with order-based comparison operators (>, <, etc.).
Adding or Changing Items:
- Using [key] = value enclosed in square brackets: The value of the key is updated if it exists. A new key-value pair is added in the event that the key is not present.
- By using the update() method, key-value pairs from an iterable or another dictionary are added to the dictionary. New keys are added, and existing keys are updated.
Deleting Items:
- By using the del keyword, the object with the designated key is removed.
- Making use of the pop(key) function: This method returns the value of the supplied key and removes the item.
- In Python 3.7+, the popitem() function eliminates the last inserted item and returns an arbitrary (key, value) pair.
Getting Views: Obtaining Views (values(), items(), and keys()): The current status of the dictionary’s keys, values, or key-value pairs (as tuples) are shown via these methods’ return view objects, which are list-like but not lists in Python.
- The dictionary can be iterated through using these views. Using a for loop to iterate over a dictionary by default iterates over the keys.
- You can use.keys(),.values(), or.items() to explicitly loop over keys, values, or key-value pairs.
- Clear(): Gets rid of everything in the dictionary.
A shallow copy of the dictionary is returned by the copy() function. A deep copy is produced via deepcopy(). - Fromkeys(seq[, value]): This function generates a new dictionary with values set to value (defaults to None) and keys from seq.
- Setdefault(key[,default]): This function is comparable to get(), but in the event that the key cannot be located, it inserts the default value (or None if it is not supplied) and returns the value.
Dictionary Keys:
One essential component of dictionaries is the key:
- Uniqueness: Every dictionary key needs to be distinct. The old value will be replaced if you attempt to add an item with an existing key.
- Immutability: Dictionary keys ought to be unchangeable entities. Strings, integers, floats, and tuples are examples of common immutable types that are used as keys. It is not possible to utilise lists or other mutable types as keys.
- Case Sensitivity: The case of dictionary keys matters. ‘Name’ and ‘name’, for instance, would be regarded as individual keys.
- Indexing: To access values, keys function similarly to indexes.
Nested Dictionaries:
Any Python object, including other dictionaries, can be the value linked to a key. This makes it possible to construct intricate data structures with dictionaries nestled inside of one another.
# Example of a nested dictionary structure
# D = {'food': {'ham': 1, 'egg': 2}}
Chaining access operations allows you to access entries in nested dictionaries.
employee data = {'manager': {'name': 'Alice', 'id': 101}, 'employee': {'name': 'Bob', 'id': 202}}
manager name = employee data['manager']['name']
print(manager name)
Alice
Advantages of Dictionaries Over Lists:
How you get the data is the primary distinction between dictionaries and lists. Whereas dictionaries are accessible by their key (a meaningful label), lists are accessed by their number index (position).
For some jobs, dictionaries are better than lists because they let you link a set of values to descriptive keys, which makes the code easier to read and comprehend. Dictionaries are more effective and semantically acceptable when you need to look up information based on a particular identity or label rather than a position.
Code Example Illustrating Advantage:
Think about keeping track of how many days there are in each month. It’s less straightforward to use a list as you have to know each month’s number index. By utilising the name of the month as the key, you may retrieve the data directly by using a dictionary.
Using a List:
# List approach
days in month list
# To get days in January (index 0):
January days list = days in month list
print(f" Days in January (list): {January days list}")
# To get days in December (index 11):
December days list = days in month list
print(f" Days in December (list): {December days list}")
# Accessing February requires remembering it's index 1
February days list = days in month list
print(f" Days in February (list): {February days list}")
Using a dictionary:
# Dictionary approach
days in month dict = {'January': 31, 'February': 28, 'March': 31, 'April': 30,
'May': 31, 'June': 30, 'July': 31, 'August': 31,
'September': 30, 'October': 31, 'November': 30, 'December': 31}
# To get days in January:
January days dict = days in month dict
print(f" Days in January (dict): {January days dict}")
# To get days in December:
December days dict = days in month dict
print(f" Days in December (dict): {December days dict}")
# Accessing February is intuitive using its name
February days dict = days in month dict
print(f" Days in February (dict): {February days dict}")
Using the month name as a key in the dictionary to retrieve the number of days is considerably more readable and eliminates the need to recall the month’s place in a list, as demonstrated in the example. When you have a collection of data with distinct, meaningful identifiers for each item that you wish to utilise for retrieval, dictionaries are perfect.