Skip to main content

How to Convert a List of Tuples to a Dictionary in Python

Converting a list of tuples to a dictionary is a fundamental data transformation task in Python. While the dict() constructor handles simple cases directly, real-world data often contains duplicate keys that require special handling, since by default later values silently overwrite earlier ones.

In this guide, you will learn how to perform basic conversions, group values under duplicate keys, aggregate data, and transform keys or values during the conversion process.

Simple Conversion with dict()

For lists where each tuple contains a unique key and a value, pass the list directly to dict():

items = [("apple", 0.99), ("banana", 0.59), ("cherry", 1.50)]

prices = dict(items)

print(prices)
print(prices["apple"])

Output:

{'apple': 0.99, 'banana': 0.59, 'cherry': 1.5}
0.99

From enumerate() Output

The enumerate() function produces (index, value) tuples, which convert directly into an index-keyed dictionary:

fruits = ["apple", "banana", "cherry"]

indexed = dict(enumerate(fruits))

print(indexed)

Output:

{0: 'apple', 1: 'banana', 2: 'cherry'}

Reversing Keys and Values

To swap keys and values during conversion, use a dictionary comprehension:

items = [("a", 1), ("b", 2), ("c", 3)]

reversed_dict = {v: k for k, v in items}

print(reversed_dict)

Output:

{1: 'a', 2: 'b', 3: 'c'}

Handling Duplicate Keys

The default dict() constructor keeps only the last value for any duplicate key, silently discarding earlier entries:

data = [("a", 1), ("b", 2), ("a", 3)]

result = dict(data)
print(result)

Output:

{'a': 3, 'b': 2}

The first ("a", 1) pair is lost without any warning. The following sections show how to preserve all values instead.

Grouping Values into Lists with defaultdict

To keep all values associated with each key, collect them into lists:

from collections import defaultdict

events = [
("user1", "login"),
("user2", "login"),
("user1", "purchase"),
("user1", "logout"),
("user2", "logout")
]

grouped = defaultdict(list)

for user, action in events:
grouped[user].append(action)

print(dict(grouped))

Output:

{'user1': ['login', 'purchase', 'logout'], 'user2': ['login', 'logout']}

Summing Values for Duplicate Keys

from collections import defaultdict

sales = [
("Alice", 100),
("Bob", 150),
("Alice", 200),
("Charlie", 75),
("Bob", 50)
]

totals = defaultdict(int)

for name, amount in sales:
totals[name] += amount

print(dict(totals))

Output:

{'Alice': 300, 'Bob': 200, 'Charlie': 75}

Counting Occurrences

from collections import defaultdict

votes = [
("Python", 1),
("JavaScript", 1),
("Python", 1),
("Python", 1),
("JavaScript", 1)
]

counts = defaultdict(int)
for item, count in votes:
counts[item] += count

print(dict(counts))

Output:

{'Python': 3, 'JavaScript': 2}

Using setdefault() Without Imports

If you prefer to avoid importing defaultdict, the built-in setdefault() method provides similar functionality:

events = [
("user1", "login"),
("user2", "login"),
("user1", "logout")
]

grouped = {}
for user, action in events:
grouped.setdefault(user, []).append(action)

print(grouped)

Output:

{'user1': ['login', 'logout'], 'user2': ['login']}
note

The setdefault(user, []) call returns the existing list for that key if it already exists, or creates and inserts a new empty list if it does not.

Using Dictionary Comprehension

Dictionary comprehensions let you transform keys or values during conversion:

raw = [("  name ", " Alice "), ("  role ", " admin ")]

clean = {k.strip(): v.strip() for k, v in raw}
print(clean)

Output:

{'name': 'Alice', 'role': 'admin'}

Filtering During Conversion

items = [("a", 1), ("b", -2), ("c", 3), ("d", -4)]

positive = {k: v for k, v in items if v > 0}
print(positive)

Output:

{'a': 1, 'c': 3}

Converting Value Types

prices = [("apple", "0.99"), ("banana", "0.59"), ("cherry", "1.50")]

prices_dict = {item: float(price) for item, price in prices}
print(prices_dict)

Output:

{'apple': 0.99, 'banana': 0.59, 'cherry': 1.5}

Handling Tuples with More Than Two Elements

When tuples contain three or more elements, you need to decide how to structure the dictionary values:

records = [
("Alice", 25, "Engineer"),
("Bob", 30, "Designer"),
("Charlie", 35, "Manager")
]

# Keep remaining elements as a tuple
people = {name: (age, role) for name, age, role in records}
print(people)

# Or convert to a nested dictionary for named access
people_detailed = {
name: {"age": age, "role": role}
for name, age, role in records
}
print(people_detailed)

Output:

{'Alice': (25, 'Engineer'), 'Bob': (30, 'Designer'), 'Charlie': (35, 'Manager')}
{'Alice': {'age': 25, 'role': 'Engineer'}, 'Bob': {'age': 30, 'role': 'Designer'}, 'Charlie': {'age': 35, 'role': 'Manager'}}

Using Named Tuples for Structured Access

For records that you will access frequently by field name, namedtuple provides self-documenting, readable access:

from collections import namedtuple

Person = namedtuple('Person', ['name', 'age', 'role'])

records = [
("Alice", 25, "Engineer"),
("Bob", 30, "Designer")
]

people = {name: Person(name, age, role) for name, age, role in records}

print(people["Alice"].role)
print(people["Alice"].age)

Output:

Engineer
25

Converting Nested Tuples to Nested Dictionaries

When your data contains tuples nested within tuples, apply dict() recursively:

data = [
("user1", [("setting1", "value1"), ("setting2", "value2")]),
("user2", [("setting1", "value3")])
]

result = {user: dict(settings) for user, settings in data}

print(result)

Output:

{'user1': {'setting1': 'value1', 'setting2': 'value2'}, 'user2': {'setting1': 'value3'}}

Practical Example: Processing Database Results

A common real-world scenario is aggregating rows returned from a database query:

from collections import defaultdict

# Simulated database rows: (user_id, order_id, amount)
orders = [
(1, 101, 99.99),
(2, 102, 149.50),
(1, 103, 75.00),
(1, 104, 200.00),
(2, 105, 50.00)
]

# Aggregate totals and collect order details per user
user_totals = defaultdict(float)
user_orders = defaultdict(list)

for user_id, order_id, amount in orders:
user_totals[user_id] += amount
user_orders[user_id].append({"order_id": order_id, "amount": amount})

print("Totals:", dict(user_totals))
print("Orders:", dict(user_orders))

Output:

Totals: {1: 374.99, 2: 199.5}
Orders: {1: [{'order_id': 101, 'amount': 99.99}, {'order_id': 103, 'amount': 75.0}, {'order_id': 104, 'amount': 200.0}], 2: [{'order_id': 102, 'amount': 149.5}, {'order_id': 105, 'amount': 50.0}]}

Reverse Operation: Dictionary Back to List of Tuples

To convert a dictionary back to a list of tuples, use the .items() method:

prices = {'apple': 0.99, 'banana': 0.59, 'cherry': 1.50}

items = list(prices.items())
print(items)

Output:

[('apple', 0.99), ('banana', 0.59), ('cherry', 1.5)]

Quick Reference

GoalMethodDuplicate Key Behavior
Unique keysdict(tuples)Last value wins
Group into listsdefaultdict(list)All values preserved
Sum valuesdefaultdict(int) or defaultdict(float)Accumulated total
Count occurrencesdefaultdict(int)Frequency count
Transform during conversionDict comprehensionCustomizable
No imports neededsetdefault()All values preserved

Conclusion

Converting a list of tuples to a dictionary in Python is straightforward for simple cases with dict(), but requires more thought when duplicate keys are involved. Use dict() for simple, unique-key conversions as it is the fastest and most readable option. For aggregation tasks like grouping, summing, or counting, collections.defaultdict eliminates boilerplate key-existence checks and makes your intent clear. When you need filtering or type conversion during the transformation, dictionary comprehensions provide the most flexibility.

Best Practice

Always consider whether your data might contain duplicate keys before choosing dict(). If duplicates are possible and you simply use dict(tuples), earlier values will be silently lost. Use defaultdict(list) to group, defaultdict(int) to sum or count, or setdefault() when you want to avoid the import.