Skip to content

Feat: add the to_dict() - #1288

Merged
asvetlov merged 7 commits into
aio-libs:masterfrom
rodrigobnogueira:feat/to-dict
Sep 13, 2026
Merged

asvetlov merged 7 commits into
aio-libs:masterfrom
rodrigobnogueira:feat/to-dict

Conversation

@rodrigobnogueira

Copy link
Copy Markdown
Member

What do these changes do?

Implement to_dict() methods for MultiDict, CIMultiDict, MultiDictProxy, and CIMultiDictProxy. This method groups values with the same key into a list.

Implementation Details

  • C Extension: Added multidict_to_dict in _multidict.c with direct PyDict and PyList manipulation for performance.
  • Python Fallback: Added generic to_dict in _multidict_py.py.
  • Tests: Added comprehensive test coverage in tests/test_to_dict.py, including verification of order preservation, case-insensitivity, mixed types, and proxy mutation isolation.
  • Memory Safety: Added a new isolated leak check (tests/isolated/multidict_to_dict.py) and integrated it into the CI suite (tests/test_leaks.py). Validated with intentional leak inserted in code (removed after test).

Example

md = MultiDict([("a", 1), ("b", 2), ("a", 3)])
md.to_dict()

# Result: {'a': [1, 3], 'b': [2]}

Are there changes in behavior for the user?

No existing behavior changes. This adds a new method to_dict()

Related issue number

Fixes #783 (Add to_dict method)

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes

Comment thread tests/isolated/multidict_pop.py Fixed
@codspeed

codspeed Bot commented Jan 25, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 10.87%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

❌ 3 regressed benchmarks
✅ 245 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_multidict_getall_str_hit[cs-c] 33.8 ms 38.1 ms -11.3%
❌ test_cimultidict_getall_istr_hit[c] 32.6 ms 36.7 ms -11.29%
❌ test_multidict_getall_str_hit[ci-c] 35.1 ms 39 ms -10.03%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing rodrigobnogueira:feat/to-dict (bc63ab1) with master (cc8c06a)

Open in CodSpeed

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Jan 25, 2026
@codecov

codecov Bot commented Jan 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (cc8c06a) to head (bc63ab1).

Additional details and impacted files
@@            Coverage Diff             @@
##            master     #1288    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           29        31     +2     
  Lines         4259      4449   +190     
  Branches       324       337    +13     
==========================================
+ Hits          4259      4449   +190     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rodrigobnogueira

Copy link
Copy Markdown
Member Author

About the Coveralls Coverage Metrics
Coveralls report shows "40.44% coverage on new lines". Coveralls is reporting MyPy type precision coverage, not pytest test execution coverage.

@rodrigobnogueira

rodrigobnogueira commented Jan 26, 2026 •

Copy link
Copy Markdown
Member Author
"""Benchmark comparing C vs Python implementation of to_dict()."""

import timeit
import gc
from multidict._multidict import MultiDict as CMultiDict
from multidict._multidict_py import MultiDict as PyMultiDict


def create_multidict(cls, num_keys: int, vals_per_key: int):
    items = [(f"key{i % num_keys}", f"value{i}") for i in range(num_keys * vals_per_key)]
    return cls(items)


def benchmark_to_dict(md, iterations: int = 1000) -> float:
    # Disable GC during timing to reduce noise
    gc_old = gc.isenabled()
    gc.disable()
    try:
        def run():
            md.to_dict()
        return timeit.timeit(run, number=iterations)
    finally:
        if gc_old:
            gc.enable()


def run_benchmark(num_keys: int, vals_per_key: int, iterations: int = 1000) -> None:
    total_items = num_keys * vals_per_key
    c_md = create_multidict(CMultiDict, num_keys, vals_per_key)
    py_md = create_multidict(PyMultiDict, num_keys, vals_per_key)
    
    c_time = benchmark_to_dict(c_md, iterations)
    py_time = benchmark_to_dict(py_md, iterations)
    
    speedup = py_time / c_time if c_time > 0 else 0
    
    print(f"| {num_keys:>6} | {vals_per_key:>6} | {total_items:>7} | {c_time*1000:>10.2f} | {py_time*1000:>10.2f} | {speedup:>7.2f}x |")


def main() -> None:
    print("\n" + "=" * 80)
    print("to_dict() Benchmark: C Extension vs Pure Python")
    print("=" * 80)
    print(f"\n{'Iterations per test:':30} 1000")
    print(f"{'Time unit:':30} milliseconds (total for 1000 calls)\n")
    
    print("|  Keys  | V/Key  |  Total  |   C (ms)   |   Py (ms)  | Speedup |")
    print("|--------|--------|---------|------------|------------|---------|")
    
    scenarios = [
        (10, 1),
        (10, 10),
        (100, 10),
        (1000, 10),
        (100, 100),
        # Larger datasets to target >2s execution time for Python
        (2000, 20),   # 40,000 items
        (5000, 10),   # 50,000 items
    ]
    
    for num_keys, vals_per_key in scenarios:
        run_benchmark(num_keys, vals_per_key)
    
    print("\n" + "=" * 80)
    print("Speedup = Python time / C time (higher is better for C)")
    print("=" * 80 + "\n")


if __name__ == "__main__":
    main()

to_dict() Benchmark: C Extension vs Pure Python

Iterations per test: 1000
Time unit: milliseconds (total for 1000 calls)

Keys V/Key Total C (ms) Py (ms) Speedup
10 1 10 0.73 1.77 2.43x
10 10 100 3.58 9.16 2.56x
100 10 1000 37.63 93.52 2.49x
1000 10 10000 456.58 858.80 1.88x
100 100 10000 315.51 715.76 2.27x
2000 20 40000 1694.38 3462.59 2.04x
5000 10 50000 2684.84 4875.64 1.82x

=====================================
Speedup = Python time / C time (higher is better for C)

@rodrigobnogueira
rodrigobnogueira marked this pull request as ready for review January 26, 2026 02:27

@Vizonex Vizonex left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would've applied some smarter logic like traverse all keys and gathering all the values up with something like getall(...) when going over keys since it would be a bit faster due to less time needing to check weather or not something is a list. Otherwise I think this is a good start in the right direction. There might be a quicker method though that you can try which I've attempted to visualize for you although I haven't benchmarked it but just incase here was my idea.

It's advantages mainly revolve around not needing to check on weather or not a key has already been used.

from multidict import MultiDict
# incase you need a visual of the logic I'm trying to explain
def to_dict(md: MutliDict[str]):
    return {k: md.getall(k) for k in md.keys()}

@rodrigobnogueira

rodrigobnogueira commented Jan 27, 2026 •

Copy link
Copy Markdown
Member Author

Hello @Vizonex ,

I've posted about using getall in this comment: #783 (comment)

I haven't look into the getall details yet, but it's not viable to use it as-is in the to_dict() transformation:
I couldn't even run the most demanding cases of the benchmark I posted in a previous message.

Using the getall function we get:

================================================================================
to_dict() Benchmark: C Extension vs Pure Python

Iterations per test: 1000
Time unit: milliseconds (total for 1000 calls)

Keys V/Key Total C (ms) Py (ms) Speedup
10 1 10 0.93 18.91 20.27x
10 10 100 5.66 495.79 87.56x
100 10 1000 41.58 4644.99 111.72x
1000 10 10000 424.65 53012.13 124.84x

================================================================================
Speedup = Python time / C time (higher is better for C)

Comment thread tests/test_to_dict.py Fixed

@Vizonex Vizonex left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Converter looks good. I have no complaints with this one. Great job with the pytest module also.

Comment thread CHANGES/783.feature Resolved
Comment thread tests/test_to_dict.py Resolved
Comment thread tests/test_to_dict.py Resolved
@webknjaz
webknjaz requested review from Dreamsorcerer and bdraco and removed request for asvetlov April 29, 2026 12:52
@webknjaz

Copy link
Copy Markdown
Member

@rodrigobnogueira note that there's no need to use conventional commit prefixes as they only eat up space. Towncrier uses change note-based identifiers in file names.

@Dreamsorcerer

Copy link
Copy Markdown
Member

@rodrigobnogueira Do you think anything here could be pulled into aio-libs/aiohttp#7679?

@Dreamsorcerer

Copy link
Copy Markdown
Member

@rodrigobnogueira Do you think anything here could be pulled into aio-libs/aiohttp#7679?

I'm guessing probably not, as it produces a list, rather than a concatenated string. I wonder how useful this feature will actually be (i.e. a user could just use a dict of lists in the first place if that's what they want...).

Comment thread tests/test_to_dict.py Fixed
@rodrigobnogueira

rodrigobnogueira commented May 3, 2026 •

Copy link
Copy Markdown
Member Author

@rodrigobnogueira Do you think anything here could be pulled into aio-libs/aiohttp#7679?

I'm guessing probably not, as it produces a list, rather than a concatenated string. I wonder how useful this feature will actually be (i.e. a user could just use a dict of lists in the first place if that's what they want...).

I opened this PR a few months ago to address the 2022 issue requesting this feature. If this isn't the direction we want to take, I’m fine with closing it alongside #783 to avoid adding unnecessary complexity to the library.

The value of this feature is probably a more performant to_dict method, that doesn't use the self.getall described in the issue.

@rodrigobnogueira
rodrigobnogueira requested a review from webknjaz May 3, 2026 02:09
@Dreamsorcerer

Copy link
Copy Markdown
Member

If this isn't the direction we want to take, I’m fine with closing it alongside #783 to avoid adding unnecessary complexity to the library.

I don't have a strong opinion, though it'd be nice to know if this is a somewhat common usecase for people. I'll let someone else decide if this is a good idea or not.

@Vizonex

Vizonex commented Jun 23, 2026

Copy link
Copy Markdown
Member

If this isn't the direction we want to take, I’m fine with closing it alongside #783 to avoid adding unnecessary complexity to the library.

I don't have a strong opinion, though it'd be nice to know if this is a somewhat common usecase for people. I'll let someone else decide if this is a good idea or not.

@Dreamsorcerer I think it would be good for libraries such as msgspec to have this feature implemented. I could see some use-cases such as sterilizing header files for debugging an http request for instance or for other configuration systems.

@rodrigobnogueira

Copy link
Copy Markdown
Member Author

If this isn't the direction we want to take, I’m fine with closing it alongside #783 to avoid adding unnecessary complexity to the library.

I don't have a strong opinion, though it'd be nice to know if this is a somewhat common usecase for people. I'll let someone else decide if this is a good idea or not.

@Dreamsorcerer I think it would be good for libraries such as msgspec to have this feature implemented. I could see some use-cases such as sterilizing header files for debugging an http request for instance or for other configuration systems.

Use-case evidence, since that was the open question: this mirrors an established convenience on multidict-shaped types. Werkzeug's MultiDict has exactly this as to_dict(flat=False), and Django's QueryDict exposes it through .lists().
The request in #783 came from the litestar author, and the typical situation is not one where the user could have started with a dict of lists: the multidict arrives from a library, parsed headers or query strings, and needs exporting for JSON, test comparison, or msgspec/pydantic input, as @Vizonex mentioned. The C implementation also beats the naive getall() comprehension by a wide margin (benchmarks above).

Meanwhile all review notes are addressed, to_dict() is now documented in the API reference, and the full suite is green on 3.12 and 3.13t.

@greptile-apps

greptile-apps Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

No blocking failure remains; the change is safe to merge.

No accepted P0 or P1 findings remain. The public conversion behavior passed on both the C-extension and pure-Python implementations, and the earlier mutation path now rejects the reentrant change.

T-Rex T-Rex Logs

What T-Rex did

  • Ran a standalone reproducer with MULTIDICT_NO_EXTENSIONS=1 against the parent and the current checkout, confirming that before the fix to_dict() produced a static mapping and after the fix the operation raises RuntimeError: Dictionary changed during iteration; a focused pure-Python regression test also passed with two parametrizations.
  • Executed a review-authored script covering multiple multidict scenarios, and the test suite ran clean across both the C-extension import path and a forced pure-Python implementation, with the focused tests/test_to_dict.py suite showing 56 passing tests.
  • Compared the pre-fix and post-fix to_dict behavior, noting that before the fix to_dict_return existed and after the checkout to_dict_exception RuntimeError was raised; the authored source and its execution output are retained as artifacts.
  • Captured review-script sources and test outputs were retained as artifacts for inspection and verification.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (5): Last reviewed commit: "Apply suggestions from code review" | Re-trigger Greptile

Comment thread tests/test_to_dict.py Resolved
Comment thread multidict/_abc.py Resolved
Comment thread multidict/_multidict.c Resolved
Comment thread multidict/_multidict.c Resolved
to_dict() returns a plain dict mapping every key to the list of all its
values, grouped by key identity, for MultiDict, CIMultiDict and both
proxies. Unlike dict(md) it keeps every value, and unlike a getall()
comprehension it emits one entry per case-insensitive key.

Squashed onto master after the clang-format 23 restyle.
Replaces the second dict that mapped identity to value list. md_to_dict()
walks the entries in insertion order and, for each key it has not collected
yet, gathers that key's values the way md_get_all() does, leaving the visit
marks in place so the key's later duplicates test as collected, and clearing
every mark once at the end.

The marks are held only over the value walk, which runs no Python. Building
the keys and filling the result dict both can: a str subclass may run its
own __hash__, __eq__ or __del__ from there, and a marked entry reads as a
different hash, so code re-entering the multidict would find the collected
keys missing and could strand entries the next resize indexes by a marked
hash. Those two steps therefore run afterwards, over the positions the walk
recorded, with nothing marked, and a mutation from there is refused the way
it is during iteration.
getall() already returns a new list.
Adds the cases the new walk needs: lookups still work once to_dict() has
marked and unmarked every entry, deleted entries are skipped, a key's
__hash__ sees the whole multidict, and mutating from it is refused. Covers
MultiMapping.to_dict() with a mapping that only the ABC serves.

Drops the future import and the docstrings that restated the test names,
and stops binding the unused to_dict() result in the leak script.
Comment thread tests/test_to_dict.py Fixed
Comment thread tests/test_to_dict.py Fixed
Comment thread tests/test_to_dict.py Fixed
Comment thread tests/test_to_dict.py Fixed
Comment thread tests/test_to_dict.py Fixed
Comment thread tests/test_to_dict.py Fixed
Comment thread multidict/_multidict_py.py Resolved
Building and hashing a key runs a str subclass's own code, and the C walk
already refuses a mutation made from there. The pure-Python one accepted it
and folded the result in, so the two backends disagreed on the same input.
It now raises the same way iterating does.

The C check moves to the end of each step, which is where it has to be
anyway: a mutation can move the table, and the next step reads an entry by
position.
Comment thread tests/test_to_dict.py Fixed
Comment thread tests/test_to_dict.py Fixed
Takes the multidict from the fixture rather than the C class, so the case
runs against the pure-Python build too. Gives the key classes the __eq__
that goes with overriding __hash__, and drops the overloads from the test
mapping, whose signatures are narrow enough to state directly.

@asvetlov asvetlov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Comment thread docs/multidict.rst Resolved
Comment thread docs/multidict.rst Resolved
@asvetlov
asvetlov enabled auto-merge (squash) September 13, 2026 19:07
@asvetlov

Copy link
Copy Markdown
Member

Great job!
Thanks, @rodrigobnogueira

@asvetlov
asvetlov merged commit 1f8fef9 into aio-libs:master Sep 13, 2026
55 of 57 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enhancement: to_dict method

6 participants