0

I am trying to create 10 instances of my class Rooms by taking user input which contains a number , a dictionary and a string value , this is my code :

class Rooms:

    def __init__(self, number, items, hotelname): 
        self.number = number
        self.items = items
        self.hotelname = hotelname

    @classmethod
    def from_input(cls):
        return cls(
            input('ID of Rooms: '),
            dict(input('enter commodities with price \n').split() for _ in range(5)), 
            str(input('name of hotel ')),
        )
def main():

    rooms = {}
    for _ in range(10):  # create 10 rooms
        room = Rooms.from_input()  # from room input
        rooms[room.items] = room  # and store them in the dictionary

if __name__=="__main__": 
    main()         

I'm getting the error in linerooms[room.items] = room # and store them in the dictionary as TypeError: unhashable type: 'dict'. I'm a noob in programming. I searched a lot of posts but didn't understand what I'm doing wrong. Can this not be done? My final goal is to Print out each room along with the individual items and values.

Devarshi Goswami
  • 1,035
  • 4
  • 11
  • 26
  • Your dictionary keys have to immutable, like strings, numbers, tuples, etc. A dictionary can't be a key for another dictionary. – ngShravil.py May 22 '20 at 15:23

2 Answers2

1

You are using a dictionary as a key:

rooms[room.items] = room

This is not possible as dictionaries are not hashable and they are mutable. Although, I don't know why you want to use a dictionary as a key, as a solution you can flatten your dictionary into tuples:

rooms[tuple(sorted(room.items))] = room

Then your code will work fine.

Code Pope
  • 5,075
  • 8
  • 26
  • 68
1

Please consider the point, that I said in comments.

Your dictionary keys have to immutable, like strings, numbers, tuples, etc. A dictionary can't be a key for another dictionary.

If you want to create 10 instance of the class, then you can store it in a list. Something like below:

rooms = []
for _ in range(10):
    room = Rooms.from_input()
    rooms.append(room)

Or if you still want to use dictionary as a key, then you can use frozenset() method, like below:

rooms = {}
for _ in range(10):
    room = Rooms.from_input()
    rooms[frozenset(room.items())] = room 
ngShravil.py
  • 4,742
  • 3
  • 18
  • 30