2

I have a dictionary like this:

d = {'item1': ('Hi', (150, 495)), 'item2': ('Hola', (590, 40))}

I want to convert it to object, recursively if possible. I have a class:

class Item:
    def __init__(self,thetuple):
    self.greeting=thetuple[0]
    self.coordinate=thetuple[1]

So what I want is, there should be an object, for instance item1, and item1.greeting is "Hi", item1.coordinate is (150,495) etc.

I'm open to all kinds of solutions, improvements, ideas. Thanks.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Irem
  • 43
  • 1
  • 8
  • 4
    *recursively*? There is nothing recursive in the data... Recursion should be used for things that have an inductive nature. – Willem Van Onsem Jan 02 '18 at 22:27
  • 2
    This is a simple iteration through the dictionary, forming an object from each dictionary entry. Where are you stuck? – Prune Jan 02 '18 at 22:29
  • @WillemVanOnsem Professor asked us to take this dictionary and turn each key to an object in a function,with recursion. If I understood you correctly, the answer is there is no recursion in the data because I couldn't implement it. – Irem Jan 02 '18 at 22:41
  • @Prune I'm exactly stuck at that part, I try iteration but I must be doing something wrong. – Irem Jan 02 '18 at 22:43

1 Answers1

3

You're looking for a collections.namedtuple.

So do something like this:

import collections

Item = collections.namedtuple('Item', ('greeting', 'coordinate'))

d = {'item1': ('Hi', (150, 495)), 'item2': ('Hola', (590, 40))}

new_d = {k: Item(*v) for k, v in d.items()}

# Now you can do

new_d['item1'].greeting == 'Hi'

new_d['item2'].coordinate == (590, 40)
Artyer
  • 31,034
  • 3
  • 47
  • 75