Both dict() and {} create dictionaries in Python, but they differ in usage. {} is a concise literal syntax ideal for static key-value pairs. In this article, we will check the basic difference between Python - dict() or dict{}.
dict {} - Dictionary Literal
The dict{} is a literal or direct way to create a dictionary in Python. It's an easy and fast method to define key-value pairs within curly braces. It is commonly used when you know the keys and values ahead of time and want to directly define them in the code.
Syntax:
{key1: value1, key2: value2, ...
Example:
a = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(a)
Output
{'name': 'Alice', 'age': 30, 'city': 'New York'}
dict() - Dictionary Constructor
The dict() constructor is a more formal method of creating dictionaries in Python. It allows you to pass key-value pairs as keyword arguments, where the keys are the argument names and the values are the associated arguments.
Syntax
dict(key1=value1, key2=value2, ...)Note : Unlike the
{}literal syntax, which is a more casual and direct way of creating dictionaries,dict()is a formal approach that uses a function to construct the dictionary.
Example:
name = 'GeeksforGeeks'
age = 30
city = 'New York'
# Using dict() constructor with variables
my_dict = dict(name=name, age=age, city=city)
print(my_dict)
Output
{'name': 'GeeksforGeeks', 'age': 30, 'city': 'New York'}
Comparison Between dict() vs { }
Aspects | dict() | { } |
|---|---|---|
Syntax and Style |
|
|
Flexibility | Best used when the keys and values are known ahead of time and are hardcoded directly into the dictionary. | More flexible as it allows you to dynamically generate dictionaries, for example, using variables or expressions. |
Readability and Use Cases | Easier to read and more concise when you need a dictionary with predefined, hardcoded key-value pairs. | More useful for dynamically constructed dictionaries or when keys are variable names or generated programmatically. |
Performance | Slightly faster for creating small, static dictionaries because it's a simpler, direct syntax without function overhead. | May be a bit slower, as it involves a function call, but this difference is usually negligible unless you're creating very large numbers of dictionaries dynamically. |