Table of Contents | |
Understanding Python dict()
Function
Python dict() function is a built-in function that creates a new dictionary. A dictionary in Python is a collection of key-value pairs, where each key is unique and used to access its associated value. You can think of a dictionary like a real-world dictionary, where words are the keys and their definitions are the values. Python dict() provides a flexible way to create empty or populated dictionaries with initial key-value pairs using keyword arguments, iterables, or mapping objects.
Syntax of Python dict
()
dict
()dictionary = dict(iterable, **kwarg)
Explanation
dictionary
: Variable will store the newly created dictionary.dict()
: Built-in function that creates a dictionary.iterable
(optional): Iterable object (e.g., list of tuples) containing key-value pairs. It is used as input fordict()
.**kwarg
(optional): Keyword arguments representing key-value pairs.
Example of Python dict
()
dict
()my_dict = dict()
print(my_dict)
Explanation
my_dict = dict()
: Creates an empty dictionary namedmy_dict
usingdict()
.print(my_dict)
: Prints the empty dictionary.
Output
{}
dict()
Parameters
Python dict() function can accept different parameters to create a dictionary. You can pass keyword arguments, where each argument’s name becomes a key, and its value becomes the associated value. You can also pass an iterable, such as a list of tuples, where each tuple represents a key-value pair. Additionally, you can pass a mapping object, like another dictionary, to create a new dictionary with the same key-value pairs. Dict() creates an empty dictionary if you don’t pass any arguments.
Syntax
dictionary = dict(iterable, **kwarg)
Example
my_dict = dict(name="Alice", age=30, city="New York")
print(my_dict)
Explanation
my_dict = dict(name="Alice", age=30, city="New York")
: Creates a dictionarymy_dict
using keyword arguments.print(my_dict)
: Prints the dictionary.
Output
{‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’}
dict()
Return Value
Python dict() function always returns a new dictionary. If you call it without any arguments, it returns an empty dictionary. If you provide it with keyword arguments, an iterable of key-value pairs, or a mapping object, it returns a dictionary populated with those key-value pairs. Importantly, when you pass an existing dictionary to dict()
, it doesn’t return the same dictionary but creates a shallow copy of it.
Example
empty_dict = dict()
print(empty_dict)
Explanation
empty_dict = dict()
: Creates an empty dictionary usingdict()
and assigns it toempty_dict
.print(empty_dict)
: Prints the empty dictionary.
Output
{}
Create Dictionary Using keyword arguments
One way to create a dictionary using Python dict() is by passing keyword arguments. Each keyword argument you pass becomes a key-value pair in the new dictionary. The keyword becomes the key (as a string), and the value you assign to it becomes the value associated with that key. This method is convenient when you have a few known key-value pairs to put into a dictionary.
Syntax
dictionary = dict(key1=value1, key2=value2, …)
Explanation
dictionary
: Variable will store the dictionary created using keyword arguments.dict()
: Function constructs the dictionary.key1=value1, key2=value2, ...
: Keyword arguments, each defining a key-value pair. Eachkey
will be converted to string andvalue
will be its associated value.
Example
person = dict(name="Bob", age=25, occupation="Engineer")
print(person)
Explanation
person = dict(name="Bob", age=25, occupation="Engineer")
: Creates a dictionaryperson
using keyword arguments.print(person)
: Prints theperson
dictionary.
Output
{‘name’: ‘Bob’, ‘age’: 25, ‘occupation’: ‘Engineer’}
Creating deep-copy of the dictionary using dict()
Passing an existing dictionary to Python dict() creates a shallow copy of that dictionary. This means that the new dictionary refers to the same values as the original one, but modifying those values does not affect the other one. You can use the deepcopy() method from the copy module if you want a deep copy.
Example
original_dict = {'a': 1, 'b': 2}
copied_dict = dict(original_dict)
print(copied_dict)
Explanation
original_dict = {'a': 1, 'b': 2}
: Creates a dictionary namedoriginal_dict
.copied_dict = dict(original_dict)
: Creates a shallow copy oforiginal_dict
namedcopied_dict
.print(copied_dict)
: Prints thecopied_dict
.
Output
{‘a’: 1, ‘b’: 2}
Create Dictionary Using Iterable
You can create a dictionary using Python dict() by passing an iterable as an argument. The iterable should yield items that are themselves iterables with exactly two elements each, representing the key and the value for each entry in the dictionary. For instance, you can use a list of tuples, where each tuple contains a key-value pair. This allows you to build dictionaries from dynamically generated sequences of key-value pairs.
Syntax
dictionary = dict(iterable)
Explanation
dictionary
: Variable will hold the new dictionary created from the iterable.dict()
: Function constructs the dictionary.iterable
: Iterable object (e.g., a list of tuples) where each element is a key-value pair. It is used as input fordict()
.
Example
pairs = [("name", "Alice"), ("city", "Toronto")]
my_dict = dict(pairs)
print(my_dict)
Explanation
pairs = [("name", "Alice"), ("city", "Toronto")]
: Creates a list of tuples, each representing a key-value pair.my_dict = dict(pairs)
: Creates a dictionarymy_dict
from thepairs
list.print(my_dict)
: Prints the created dictionarymy_dict
.
Output
{‘name’: ‘Alice’, ‘city’: ‘Toronto’}
Create Dictionary Using Mapping
Passing a mapping object, such as another dictionary, to Python dict() creates a new dictionary with the same key-value pairs. This is similar to creating a shallow copy of the original dictionary. Changes to the original mapping object after the new dictionary is created won’t affect the new dictionary, and vice versa.
Syntax
new_dictionary = dict(mapping_object)
Explanation
new_dictionary
: Variable will hold the new dictionary created from the mapping object.dict()
: Function constructs the new dictionary.mapping_object
: Mapping object, such as another dictionary, that you want to copy. It is used as input fordict()
.
Example
original = {"x": 10, "y": 20}
copy_dict = dict(original)
print(copy_dict)
Explanation
original = {"x": 10, "y": 20}
: Creates a dictionary namedoriginal
.copy_dict = dict(original)
: Creates a new dictionarycopy_dict
that’s a shallow copy oforiginal
.print(copy_dict)
: Prints thecopy_dict
.
Output
{‘x’: 10, ‘y’: 20}
Conclusion
Python dict() is a function that creates dictionaries in Python. It provides flexibility by allowing you to create dictionaries in several ways: using keyword arguments, from iterables like lists of tuples, from other dictionaries, or with no arguments to create an empty dictionary. Understanding how Python dict works with different parameter types and handles copying versus referencing existing objects is crucial for writing effective and bug-free Python code.