Open In App

Python - dict() or {}

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Python
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:

Python
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

  • Syntax: {key1: value1, key2: value2, ...}
  • It is a direct, shorthand method to create dictionaries with key-value pairs enclosed in curly braces.
  • Syntax: dict(key1=value1, key2=value2, ...)
  • It uses the dict() function where key-value pairs are passed as keyword arguments.


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.


Next Article
Article Tags :
Practice Tags :

Similar Reads