Search code examples
pythondictionarytuplesconstants

convert a dict into a (const) tuple of tuples


I want to convert a dict to a tuple of tuples

from typing import Dict, Tuple
class Data:
    def __init__(self, d: Dict[int, str]) -> None:
        self.data: Tuple[Tuple[int, str], ...] = ()
        for k, v in d.items():
            self.data += ((k, v),)

d = Data({5: "five", 4: "four"})
print(d.data)

This is somewhat similar to this question, but not identical. The reason I prefer a tuple of tuples is for const-ness. Is there a better way (or more pythonic) to achieve this?


Solution

  • It seems that this question is probably a duplicate of this, and the fourth answer there (@Tom) states it's fastest to do tuple construction of list comprehension:

    self.data: Tuple[Tuple[int, str], ...] = tuple([(k, v) for k, v in d.items()])