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.
Output:
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.
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.
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.
Output:
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.
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
zipalready 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.

