Python dict() Function: A Practical Guide With Examples

When I build a small reporting script, I often need a fast way to organize related details. For example, an employee record may need a name, department, email, and monthly sales figure. Keeping those values in separate variables becomes messy quickly.

That is where the Python dict() function helps. It creates a dictionary, which stores data as key-value pairs. A key works like a label, and its value holds the related information. You can use dictionaries in automation scripts, API responses, JSON data, configuration files, and data-processing tasks.

This practical Python tutorial shows how to use the dict() function to create, convert, update, and work with dictionaries through complete examples.

What Is the Python dict() Function?

The built-in dict() function creates a Python dictionary. A dictionary is a mutable collection, which means you can add, change, and remove data after creating it.

Here is the basic syntax:

dict()

When you call dict() without any arguments, Python creates an empty dictionary.

employee = dict()

print(employee)

Output:

{}

This is useful when your script needs to collect information gradually. For example, a local automation script may read rows from a CSV file and add one employee record at a time.

You can also create an empty dictionary with curly braces:

employee = {}

print(employee)

Output:

{}

Both options work. I usually use {} for a simple empty dictionary because it is shorter. I use dict() when I want to create a dictionary from keyword arguments, pairs, or another mapping.

If you are new to Python collections, also review the differences between lists, tuples, sets, and dictionaries. Choosing the right collection early makes scripts easier to maintain.

Create a Dictionary With Python dict()

The dict() function supports several practical ways to create dictionary data. Each option fits a different input format.

Create a dictionary with keyword arguments

The easiest dict() pattern uses keyword arguments. Write each key, followed by an equals sign and its value.

employee = dict(
name="Michael Johnson",
city="Seattle",
department="Sales",
monthly_sales=18500
)

print(employee)

Output:

{'name': 'Michael Johnson', 'city': 'Seattle', 'department': 'Sales', 'monthly_sales': 18500}

You can see the output in the screenshot below to see the output.

Python dict() Function

Python uses the names before the equals signs as dictionary keys. This format reads well when you know the fields in advance, such as an employee profile or application settings.

There is one important limitation. Keyword argument keys must follow Python variable naming rules. They cannot contain spaces, hyphens, or start with a number.

For example, this will fail:

# This code raises a SyntaxError
employee = dict(first-name="Michael")

Use curly braces when a key contains special characters:

employee = {
"first-name": "Michael",
"employee id": 1042
}

print(employee)

Output:

{'first-name': 'Michael', 'employee id': 1042}

You can see the output in the screenshot below to see the output.

dict() Function Python

Create a dictionary from key-value pairs

In real projects, data often arrives as a list of pairs. Each pair contains a key and a matching value. The dict() function turns those pairs into a dictionary.

employee_details = [
("name", "Emily Carter"),
("city", "Austin"),
("department", "Marketing"),
("monthly_sales", 14200)
]

employee = dict(employee_details)

print(employee)

Output:

{'name': 'Emily Carter', 'city': 'Austin', 'department': 'Marketing', 'monthly_sales': 14200}

This approach works well after parsing text files, reading spreadsheet rows, or transforming data from another system. Each inner tuple contains exactly two values: the key first and the value second.

You can use lists instead of tuples too:

employee_pairs = [
["name", "David Miller"],
["city", "Chicago"],
["department", "Support"]
]

employee = dict(employee_pairs)

print(employee)

Output:

{'name': 'David Miller', 'city': 'Chicago', 'department': 'Support'}

You can see the output in the screenshot below to see the output.

dict() Function in Python

Pro Tip: I have found that malformed source data causes most dict() conversion errors. Before converting pairs, confirm that every item contains exactly two values: one key and one value.

Create a dictionary with zip() and dict()

A common automation task involves two related lists. One list contains field names and the other contains values. The built-in zip() function joins matching items, and dict() converts them into a dictionary.

fields = ["name", "city", "department", "monthly_sales"]
values = ["Sarah Williams", "Denver", "Operations", 12600]

employee = dict(zip(fields, values))

print(employee)

Output:

{'name': 'Sarah Williams', 'city': 'Denver', 'department': 'Operations', 'monthly_sales': 12600}

This pattern is useful when you read a spreadsheet header row and then process each data row. For a deeper walkthrough, see how to use the Python zip() function.

Be careful when the lists have different lengths. zip() stops when it reaches the shortest list.

fields = ["name", "city", "department"]
values = ["Robert Brown", "Boston"]

employee = dict(zip(fields, values))

print(employee)

Output:

{'name': 'Robert Brown', 'city': 'Boston'}

Python silently drops "department" because there is no matching value. Validate your input before relying on this pattern in a production automation script.

Convert Data With Python dict()

The Python dict() function does more than create brand-new dictionaries. It also converts compatible data structures into dictionaries.

Copy an existing dictionary

Passing a dictionary to dict() creates a shallow copy. A shallow copy creates a new outer dictionary but keeps references to nested objects.

original_employee = {
"name": "Olivia Davis",
"city": "Portland",
"department": "Finance"
}

employee_copy = dict(original_employee)

employee_copy["city"] = "San Diego"

print("Original:", original_employee)
print("Copy:", employee_copy)

Output:

Original: {'name': 'Olivia Davis', 'city': 'Portland', 'department': 'Finance'}
Copy: {'name': 'Olivia Davis', 'city': 'San Diego', 'department': 'Finance'}

The original dictionary remains unchanged because employee_copy is a separate dictionary.

This is helpful when a script needs a base configuration and a temporary version for one specific task. You can also learn more about shallow copy versus deep copy in Python, especially when dictionaries contain nested lists or dictionaries.

Convert a list of tuples to a dictionary

A list of tuples often appears after reading database results or processing structured text. Convert it directly with dict().

sales_record = [
("salesperson", "James Wilson"),
("region", "West"),
("target", 25000),
("actual_sales", 27850)
]

sales_data = dict(sales_record)

print(sales_data)

Output:

{'salesperson': 'James Wilson', 'region': 'West', 'target': 25000, 'actual_sales': 27850}

After conversion, access a value by using its key:

print(sales_data["actual_sales"])

Output:

27850

Dictionary lookups make code clearer than remembering numeric positions in a list. "actual_sales" explains the value immediately, while record[3] does not.

Convert a string with dictionary data carefully

You may receive dictionary-style data as a string from a file, command-line input, or another system. Do not pass that string directly to dict().

text_data = "{'name': 'Daniel Harris', 'city': 'Miami'}"

# This will raise an error
# employee = dict(text_data)

Instead, if the source contains valid JSON, convert it using the json module. JSON means JavaScript Object Notation, a text format commonly used by APIs and configuration files.

import json

text_data = '{"name": "Daniel Harris", "city": "Miami", "department": "IT"}'

employee = json.loads(text_data)

print(employee)
print(employee["department"])

Output:

{'name': 'Daniel Harris', 'city': 'Miami', 'department': 'IT'}
IT

For more detail, see this guide on converting a JSON string to a Python dictionary.

Never use eval() to convert untrusted text into a dictionary. It can run harmful code and creates a serious security risk.

Use Python dict() in a Reporting Script

Let’s use a realistic example: a small sales reporting script for a U.S. company. The script receives column headings and employee values, creates a dictionary, calculates the difference from the sales target, and prints a readable report.

fields = ["name", "city", "department", "sales_target", "actual_sales"]
values = ["Jennifer Martinez", "Dallas", "Sales", 30000, 32750]

employee = dict(zip(fields, values))

employee["sales_difference"] = (
employee["actual_sales"] - employee["sales_target"]
)

print("Monthly Sales Report")
print("-" * 25)
print(f"Employee: {employee['name']}")
print(f"City: {employee['city']}")
print(f"Department: {employee['department']}")
print(f"Sales Target: ${employee['sales_target']:,}")
print(f"Actual Sales: ${employee['actual_sales']:,}")
print(f"Difference: ${employee['sales_difference']:,}")

Output:

Monthly Sales Report
-------------------------
Employee: Jennifer Martinez
City: Dallas
Department: Sales
Sales Target: $30,000
Actual Sales: $32,750
Difference: $2,750

This script uses dict(zip(fields, values)) because it mirrors how structured tabular data works. The headings become keys, and the employee row becomes values.

The script then adds a new key, "sales_difference", after creating the dictionary. Dictionaries work well for this kind of record because you can grow the data structure as your reporting needs expand.

You can use this same approach after you read an Excel file in Python or create data exports from a local script.

Access and Update dict() Values

Creating a dictionary is only the first step. Most scripts then need to read, add, or update values.

Access a dictionary value

Use square brackets and the key name to access a specific value.

employee = dict(
name="Kevin Anderson",
city="Phoenix",
department="Engineering"
)

print(employee["name"])

Output:

Kevin Anderson

This works when you know the key exists. If the key may not exist, use the get() method instead.

employee = dict(
name="Kevin Anderson",
city="Phoenix"
)

department = employee.get("department", "Not assigned")

print(department)

Output:

Not assigned

The get() method prevents a KeyError, which is an exception Python raises when code requests a missing dictionary key.

Add or update dictionary values

Assign a value to a key to add a new field or replace an existing value.

employee = dict(
name="Amanda Thompson",
city="New York",
department="Customer Success"
)

employee["email"] = "amanda.thompson@example.com"
employee["city"] = "Brooklyn"

print(employee)

Output:

{'name': 'Amanda Thompson', 'city': 'Brooklyn', 'department': 'Customer Success', 'email': 'amanda.thompson@example.com'}

The first assignment adds "email" because it does not exist. The second assignment updates "city" because that key already exists.

For more examples, see how to update values in a Python dictionary and add items to a dictionary.

Loop through a dictionary

When you need to print or process every field, use the items() method. It returns each key and value together.

employee = dict(
name="Christopher Moore",
city="Atlanta",
department="Human Resources",
active=True
)

for key, value in employee.items():
print(f"{key}: {value}")

Output:

pythonname: Christopher Moore
city: Atlanta
department: Human Resources
active: True

This is a clean pattern for console reports, log entries, and debugging output. For dictionaries with many fields, format them clearly with this guide on pretty printing a Python dictionary.

Python dict() Function vs Curly Braces

Both dict() and {} create dictionaries, but each has a useful place.

SituationBest optionExample
Create an empty dictionary{}employee = {}
Create known literal data{}{"name": "John Smith"}
Use simple named fieldsdict()dict(name="John Smith")
Convert pairs into a dictionarydict()dict([("name", "John Smith")])
Copy another dictionarydict()dict(existing_data)
Build a dictionary from two listsdict() with zip()dict(zip(keys, values))

For fixed data written directly in your code, curly braces are often more familiar. For conversions and keyword arguments, the dict() function is clearer and more flexible.

Things to Keep in Mind

  • Use valid keyword keys: Keys passed as keyword arguments must be valid Python identifiers, so use braces for keys with spaces, hyphens, or numbers at the beginning.
  • Check pair lengths: Every item passed to dict() as a pair must contain exactly two values, otherwise Python raises a ValueError.
  • Watch duplicate keys: Python keeps the last value when the same key appears more than once, which can silently overwrite important data.
  • Use get() for optional keys: The get() method avoids a KeyError when an API response or imported record lacks an expected field.
  • Avoid eval() with input: Never run eval() on dictionary-like text from users, files, or external systems; use the json module for JSON data.
  • Remember shallow copying: dict(existing_dict) copies the outer dictionary only. Nested lists and dictionaries still point to the same inner objects.

Frequently Asked Questions

What does dict() do in Python?

The dict() function creates a dictionary, which stores values under named keys. You can call it with no arguments, keyword arguments, a list of pairs, or another dictionary.

How do I create an empty dictionary using dict()?

Call the function with no arguments.
data = dict()
print(data)

Output:
{}
You can also use {}, which is the shorter and more common option.

Can I use dict() with a list?

Yes, but each item in the list must contain two values: a key and a value. A list of tuples or lists works well.
data = dict([(“city”, “Seattle”), (“state”, “Washington”)])
print(data)
Output:
{‘city’: ‘Seattle’, ‘state’: ‘Washington’}

What happens if dict() receives duplicate keys?

Python keeps the value from the last matching key. Earlier values get overwritten.
data = dict([(“city”, “Seattle”), (“city”, “Tacoma”)])
print(data)
Output:
{‘city’: ‘Tacoma’}

Is dict() the same as {} in Python?

Both create dictionaries, but dict() also converts compatible data into a dictionary. Use {} for direct dictionary literals and dict() for keyword arguments, copies, or key-value pair conversions.

How do I convert two lists into a dictionary in Python?

Use zip() to pair the lists and pass the result to dict().
keys = ["name", "department"]
values = ["Laura Taylor", "Legal"]
employee = dict(zip(keys, values))
print(employee)

Output:
{'name': 'Laura Taylor', 'department': 'Legal'}

The Python dict() function gives you a flexible way to create and convert dictionaries for scripts, reports, imported data, and API-driven applications. Start with simple keyword arguments or key-value pairs, then use zip() and safe access methods as your data becomes more dynamic.

I hope you found this practical guide helpful and feel ready to use dict() confidently in your next Python project.

You May Also Like