Python
dictionary
list conversion
data structures
key-value pairs

Convert key1,val1,key2,val2 to a dict?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you have a flat Python list shaped like key, value, key, value, the task is to group the items into consecutive pairs and pass those pairs into dict. The simplest clean solution is usually zip over every other element. The main thing to watch is input validity: the list must contain an even number of elements, or the last key or value will be left unpaired.

Simple Solution with Slicing and zip

A readable approach is to slice the keys and values separately.

python
items = ["name", "Ada", "role", "engineer", "city", "London"]
result = dict(zip(items[0::2], items[1::2]))
print(result)

Output:

python
{'name': 'Ada', 'role': 'engineer', 'city': 'London'}

This works because items[0::2] selects positions 0, 2, 4, while items[1::2] selects positions 1, 3, 5.

Validate the Input Length First

If the list length is odd, one element has no partner. That is usually a data-quality problem, so detect it early.

python
1def flat_list_to_dict(items):
2    if len(items) % 2 != 0:
3        raise ValueError("Expected an even number of list elements")
4    return dict(zip(items[0::2], items[1::2]))
5
6
7print(flat_list_to_dict(["a", 1, "b", 2]))

Explicit validation is better than silently ignoring a leftover item.

Iterator-Based Version for Large Inputs

If you want to avoid building two slices, use one iterator and consume it in pairs.

python
1def flat_list_to_dict(items):
2    if len(items) % 2 != 0:
3        raise ValueError("Expected an even number of list elements")
4
5    iterator = iter(items)
6    return dict(zip(iterator, iterator))
7
8
9print(flat_list_to_dict(["x", 10, "y", 20, "z", 30]))

This pattern is compact and memory-friendly because the iterator is advanced two items at a time.

Know What Happens with Duplicate Keys

Python dictionaries keep only one value per key. If the flat input repeats a key, the later value wins.

python
items = ["a", 1, "a", 99]
print(dict(zip(items[0::2], items[1::2])))

Output:

python
{'a': 99}

That is normal dictionary behavior, so if duplicate keys are invalid in your data, validate for that separately.

When a Different Structure Is Better

Sometimes a flat alternating list is only an intermediate format from another system such as a command-line parser or a legacy API. If you control the data source, it is often better to represent the data as:

  • a list of pairs
  • a dictionary directly
  • a structured object or dataclass

The conversion itself is easy. The harder question is whether the flat format should exist at all.

A Loop Is Fine When Validation Is Richer

If you need more checks than zip provides, an explicit loop can be easier to extend.

python
1def flat_list_to_dict_checked(items):
2    if len(items) % 2 != 0:
3        raise ValueError("Expected an even number of list elements")
4
5    result = {}
6    for index in range(0, len(items), 2):
7        key = items[index]
8        value = items[index + 1]
9        result[key] = value
10    return result

This is more verbose, but it gives you a natural place to reject duplicate keys or enforce key types.

Common Pitfalls

  • Forgetting to check that the list length is even.
  • Assuming duplicate keys will be preserved separately in a normal dictionary.
  • Building a dictionary from data whose order and pairing rules were not verified first.
  • Using a complicated loop when zip already expresses the pairing clearly.
  • Confusing a flat list with a list of two-item tuples, which needs a different conversion approach.

Summary

  • A flat alternating list can be converted with dict(zip(items[0::2], items[1::2])).
  • Validate the input length so every key has a matching value.
  • 'zip(iterator, iterator) is a compact iterator-based alternative.'
  • Duplicate keys are overwritten by the last value.
  • If you control the upstream format, consider using a more structured representation.

Course illustration
Course illustration

All Rights Reserved.