Python dict() function is for creating dictionaries. Dictionaries are collections of key-value pairs, where each key is associated with a corresponding value. You can think of them as a way to store and organize data using meaningful labels (keys) to access the information (values) you need.
dict()
Syntax
my_dictionary = dict(key1=value1, key2=value2, ...)
# OR
my_dictionary = dict(iterable)
# OR
my_dictionary = dict(mapping)
my_dictionary
: The variable that will hold the new dictionarydict()
: The built-in Python function for creating dictionarieskey1=value1, key2=value2, ...
: Keyword arguments where each key is assigned a corresponding valueiterable
: An iterable (e.g., list of tuples) where each item represents a key-value pairmapping
: Another dictionary-like object to copy key-value pairs from
Example 1: Create Dictionary Using keyword arguments
my_dict = dict(name='Bob', age=25, city='New York')
print(my_dict)
Line 1: Creates a dictionary using the dict()
function and keyword arguments to define the key-value pairs
Output
{‘name’: ‘Bob’, ‘age’: 25, ‘city’: ‘New York’}
Example 2: Create Dictionary Using Iterable
my_list = [('x', 1), ('y', 2)]
my_dict = dict(my_list)
print(my_dict)
Code Explanation
- Line 1: Creates a list of tuples, where each tuple represents a key-value pair.
- Line 2: Creates a dictionary from the iterable (list of tuples).
- Line 3: Prints the dictionary created from the list.
Output
{‘x’: 1, ‘y’: 2}
Example 3: Create Dictionary Using Mapping
my_dict1 = {'a': 1, 'b': 2}
my_dict2 = dict(my_dict1)
print(my_dict2)
Code Explanation
- Line 1: Creates a dictionary
- Line 2: Creates a new dictionary by copying the key-value pairs from another dictionary
- Line 3: Prints the new dictionary
Output
{‘a’: 1, ‘b’: 2}