Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The best conversion depends on what your list represents. Use dict(zip(keys, values)) for two parallel lists, dict(pairs) for a list of key-value pairs, a dictionary comprehension when keys or values must be calculated, and dict(enumerate(items)) when positions should become keys. Check for duplicate keys first: a normal dictionary keeps one value per key, and a later value replaces an earlier one.

These patterns use Python’s built-in dict(), zip(), enumerate(), and dictionary-comprehension syntax documented by the Python Software Foundation’s Python 3.12.14 documentation.

Choose the pattern that matches your list

Input shape Use Example result Duplicate-key behavior
Two corresponding lists dict(zip(keys, values)) {'Ada': 95} Later values overwrite earlier ones
A sequence of two-item records dict(pairs) {'Ada': 95} Later records overwrite earlier ones
One list with calculated fields Dictionary comprehension {2: 4} Later results for the same key overwrite
One list where position matters dict(enumerate(items)) {0: 'Ada'} Positions are unique

Convert two parallel lists with zip()

When one list contains keys and another contains the corresponding values in the same order, zip the lists and pass the resulting pairs to dict().

names = ["Ada", "Linus"]
scores = [95, 88]

by_name = dict(zip(names, scores))
print(by_name)
# {'Ada': 95, 'Linus': 88}

zip() pairs the first key with the first value, the second key with the second value, and so on. Use this only when the two sequences genuinely represent corresponding records; it is not a way to match items by their contents.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

What if the lists have different lengths?

Ordinary zip() stops when the shortest input is exhausted. That means extra items in a longer list are ignored.

keys = ["a", "b", "c"]
values = [1, 2]

result = dict(zip(keys, values))
print(result)
# {'a': 1, 'b': 2}

If silently dropping data would be a bug, validate the lengths before converting.

if len(keys) != len(values):
    raise ValueError("keys and values must have the same length")

result = dict(zip(keys, values))

On Python versions that provide it, zip(keys, values, strict=True) can also raise when lengths differ. Use that option when a mismatch must fail immediately.

Duplicate keys in parallel lists

keys = ["Ada", "Ada"]
values = [95, 100]

result = dict(zip(keys, values))
print(result)
# {'Ada': 100}

The second pair replaces the first because dictionary keys are unique. If every score matters, group values instead of converting directly; the grouping example appears below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert a list of key-value pairs with dict()

If the list already contains two-item tuples or lists, pass it directly to dict().

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
pairs = [("Ada", 95), ("Linus", 88)]
by_name = dict(pairs)
print(by_name)
# {'Ada': 95, 'Linus': 88}

The same pattern works with lists of lists:

records = [["Ada", 95], ["Linus", 88]]
by_name = dict(records)

Each inner item must provide exactly two values: one key and one value. A record with one item or three items raises a ValueError.

dict([("Ada", 95, "extra")])
# ValueError: dictionary update sequence element ... has length 3; 2 is required

Keys still need to be hashable. Strings, numbers, and tuples whose contents are immutable can be keys; a list cannot.

good = {(1, 2): "point"}

# TypeError: unhashable type: 'list'
bad = {[1, 2]: "point"}

Use a dictionary comprehension for calculated data

A comprehension is clearest when the key or value is transformed while you iterate over the source list.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
numbers = [2, 4, 6]
squares = {n: n * n for n in numbers}
print(squares)
# {2: 4, 4: 16, 6: 36}

You can transform strings, select fields from records, or apply a condition.

words = ["Python", "API", "web"]
lengths = {word.lower(): len(word) for word in words}

products = [
    {"sku": "A1", "price": 12.5},
    {"sku": "B2", "price": 8.0},
]
price_by_sku = {item["sku"]: item["price"] for item in products}

positive_squares = {n: n * n for n in range(-3, 4) if n > 0}

If two source items produce the same calculated key, the last result wins, just as with dict(zip(...)).

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Use list positions as dictionary keys with enumerate()

When the list has no natural key, enumerate() supplies each zero-based position.

names = ["Ada", "Linus"]
by_position = dict(enumerate(names))
print(by_position)
# {0: 'Ada', 1: 'Linus'}

Start counting at another number by passing start:

by_rank = dict(enumerate(names, start=1))
# {1: 'Ada', 2: 'Linus'}

Use positional keys when the index has meaning, such as a rank or row number. If the items have stable identifiers, those identifiers are usually a better long-term key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preserve every value for duplicate keys

A dictionary cannot hold multiple independent values under the same key. If duplicates represent meaningful records, map each key to a list and append values as you process the input.

pairs = [("Ada", 95), ("Linus", 88), ("Ada", 100)]

scores_by_name = {}
for name, score in pairs:
    scores_by_name.setdefault(name, []).append(score)

print(scores_by_name)
# {'Ada': [95, 100], 'Linus': [88]}

For a simple one-pass grouping expression, use collections.defaultdict:

from collections import defaultdict

grouped = defaultdict(list)
for key, value in pairs:
    grouped[key].append(value)

scores_by_name = dict(grouped)

Choose ordinary conversion only when replacement of earlier duplicates is the intended policy.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Filter, normalize, and validate while converting

Skip invalid or unwanted records

pairs = [("Ada", 95), ("", 70), ("Linus", 88)]
valid = {name: score for name, score in pairs if name}
# {'Ada': 95, 'Linus': 88}

Normalize keys before insertion

raw = [(" Ada ", 95), ("LINUS", 88)]
clean = {name.strip().lower(): score for name, score in raw}
# {'ada': 95, 'linus': 88}

Normalization can create collisions. For example, "Ada" and " ada " become the same key, so decide whether to reject, overwrite, or group them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reject duplicate keys explicitly

def pairs_to_unique_dict(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate key: {key!r}")
        result[key] = value
    return result

Common errors and fixes

  • Values disappear: duplicate keys were overwritten. Group values or reject duplicates before insertion.
  • Unexpected missing entries: parallel lists had different lengths and zip() stopped at the shorter one. Compare lengths or use strict zipping.
  • TypeError: unhashable type: 'list': a list was used as a key. Convert it to a tuple if its contents are immutable and a composite key is appropriate.
  • ValueError from dict(): an inner record did not contain exactly two items. Validate the input shape.
  • Wrong key choice: positions were used even though records have identifiers, or a non-unique display field was used as an identifier. Select a stable, unique field.
  • Unexpected case or whitespace collisions: key normalization merged distinct source values. Normalize deliberately and check collisions.

Performance and memory considerations

All four patterns make one dictionary from the source data and require storage for the resulting mapping. The practical choice is therefore usually about correctness and readability, not a claimed speed ranking. A comprehension avoids a separate temporary list when transforming values. zip() produces pairs lazily, while dict() consumes them to build the mapping.

If the input is a generator, conversion consumes it once. Materialize it first only if you need to inspect or reuse the source. For very large inputs, process records incrementally and decide how duplicate keys should be handled before accepting the overwrite behavior.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test the conversion contract

Tests should cover the input shape and the duplicate policy your application promises.

def test_parallel_lists():
    assert dict(zip(["a", "b"], [1, 2])) == {"a": 1, "b": 2}

def test_grouping_duplicates():
    pairs = [("a", 1), ("a", 2)]
    grouped = {}
    for key, value in pairs:
        grouped.setdefault(key, []).append(value)
    assert grouped == {"a": [1, 2]}

Or skip the browser setup

If you are documenting these Python examples and need a clean image of a rendered page, ScreenshotNeo can return a screenshot or PDF from one GET request. It accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://docs.python.org/3.12/tutorial/datastructures.html"},
    timeout=90,
)
r.raise_for_status()
open("python-dict-guide.webp", "wb").write(r.content)

See the ScreenshotNeo documentation for the other 63 options, including full-page capture, CSS selectors, dark mode, device presets, retina scale, PDF settings, custom CSS and JavaScript, click actions, waits, request blocking, cookies, headers, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture, usage data, and the OpenAPI specification. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Does converting a list to a dictionary modify the original list?

No. These patterns create a new dictionary; the source list remains a list. Mutable objects stored as values are still shared references, so changing such an object can be visible through both containers.

Can a dictionary key be a tuple?

Yes, if the tuple and all of its contents are hashable. This is useful for a composite key such as a coordinate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I keep insertion order?

Modern Python dictionaries preserve insertion order as part of the language behavior. Conversion still follows the order in which pairs are consumed, with an existing key retaining its original position when its value is replaced.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.