Immutable dictionary, only use as a key for another dictionary

前端 未结 8 2352
情歌与酒
情歌与酒 2020-12-05 04:52

I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary.

A few months ago I used this implementation: Python hashable

8条回答
  •  旧时难觅i
    2020-12-05 05:26

    You can use an enum:

    import enum
    
    KeyDict1 = enum.Enum('KeyDict1', {'InnerDictKey1':'bla', 'InnerDictKey2 ':2})
    
    d = { KeyDict1: 'whatever', KeyDict2: 1, ...}
    

    You can access the enums like you would a dictionary:

    KeyDict1['InnerDictKey2'].value  # This is 2
    

    You can iterate over the names, and get their values... It does everything you'd expect.

提交回复
热议问题