Python dict() Built in Function

The dict() function in Python is used to create a dictionary object. A dictionary is an unordered collection of key-value pairs, where each key is unique and associated with a value. The syntax of the dict() function is:

dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)

Here are a few examples of using the dict() function in Python:

Create a dictionary from keyword arguments

# create a dictionary from keyword arguments
d = dict(name="Alice", age=25, city="New York")

# print the dictionary
print(d)

The dict() function in Python is used to create a dictionary object. A dictionary is an unordered collection of key-value pairs, where each key is unique and associated with a value. The syntax of the dict() function is:

dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)

Here are a few examples of using the dict() function in Python:

Example 1: Create a dictionary from keyword arguments

# create a dictionary from keyword arguments
d = dict(name="Alice", age=25, city="New York")

# print the dictionary
print(d)

In this example, the dict() function is used to create a dictionary object from three keyword arguments: name, age, and city. The resulting dictionary object is assigned to the variable d.

The print() function is then used to display the dictionary object, which will output:

 {'name': 'Alice', 'age': 25, 'city': 'New York'}

Example 2: Create a dictionary from a mapping object

# create a mapping object
m = {"name": "Bob", "age": 30, "city": "San Francisco"}

# create a dictionary from the mapping object
d = dict(m)

# print the dictionary
print(d)

In this example, a mapping object m is created with three key-value pairs. The dict() function is then used to create a dictionary object d from the mapping object m.

The print() function is then used to display the dictionary object, which will output:

{'name': 'Bob', 'age': 30, 'city': 'San Francisco'}

Example 3: Create a dictionary from an iterable of key-value pairs

# create an iterable of key-value pairs
iterable = [("name", "Charlie"), ("age", 35), ("city", "Boston")]

# create a dictionary from the iterable
d = dict(iterable)

# print the dictionary
print(d)

In this example, an iterable object iterable is created with three key-value pairs. The dict() function is then used to create a dictionary object d from the iterable object iterable.

The print() function is then used to display the dictionary object, which will output:

{'name': 'Charlie', 'age': 35, 'city': 'Boston'}

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions