[Tutor] Mutable objects as dictionary keys: Accessing , Sorting and Using dictionary

Pushkar vaity iampushkar01 at gmail.com
Thu Apr 18 11:18:02 EDT 2019


Hi,

I am using Python 3.7 with anaconda install in PyCharm
I am trying to traverse some directories using the os module and grab some
tcl procedures and put the proc names in python dictionary as keys. Values
are some other info related to the proc.

Problem: procs found in the directories can have similar names. But python
dict keys cannot be same.
So I am using the mutable objects as the key.

For Ex:   class MyClass:

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return repr(self.name)


proc_dict[MyClass(proc_name)] = (full_file, proc_args)

This has allowed me to have same separate keys in my dictionary.
But now,

   1. I am not able to access individual dictionary values by
specifying only the key name.
   2. I am not able to use the 'in' or 'not in' operations on my
dictionary successfully.
   3. Also, I am not able to use the sorted() function on my dict
items. It gives me an error as follows:


   - for proc_name, (file_name, proc_args) in sorted(proc_dict.items()):
      - TypeError: '<' not supported between instances of 'MyClass'
and 'MyClass'

Any ideas on how I can achieve the above points?
Thanks in advance!


More information about the Tutor mailing list