0

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?

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87

3 Answers3

2

You could do tuple(d.items()).

rchome
  • 2,623
  • 8
  • 21
1

Try this:

myDict = {5:"five",4:"four"}

def dictToTuple(d):
   return tuple(d.items())

print(dictToTuple(myDict))
Finlay
  • 108
  • 10
1

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()])
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87