Python Sort Problem

I’m having trouble with a list that isn’t sorting, if anyone could take a look at the screenshot included to see if I am doing anything wrong. I have no idea why it isn’t sorting…



It is a list of object references not a list of strings. That means you sorted the references not the names.

Dang it! I did it again, got confused between the reference and string! Monster would you have an idea how to sort these? I tried a ‘sorted(List.names)’ but received an error that the names couldn’t be called on. Thanks for all your help, seems like social and you are always the ones helping me.

Yea, Monster is elite, and I’m pretty good too. :wink:

About your problem:

As stated already, you’re sorting references, not strings, hence the trouble.

So, you need to have some-sort of a mapping between the string names, and the actual object references, which is basically a dictionary:

slots_dict = {}
for obj in scene.objects:
    if "OBmenu_itslot" in
        slot_dict[] = obj

# Dictionary keys should be auto sorted in this case ... I think
for name, object in slots_dict.items():
    print name, object

@Social, I learnt a lot of BGE from you :).

@Nitefyre, as I’m not sure for what you need a sorted list, I didn’t mentioned any solution.
Socials code is pretty much what I would do. With one exception. A dictionary is not sorted in the way you want. It is sorted for fast item access. I think in Python it is a hash table. It is that fast that it is used for pretty much everything (even for Python internals).

To sort by name I suggest a combination of dictionary and list which is quite easy:

# Socials code
slots_dict = {}
for obj in scene.objects:
    if "OBmenu_itslot" in
        slot_dict[] = obj 
# now get the names from the dict
names = slot_dict.keys()
print names

So you are sorting a list of the dictionaries keys (which are the object names).

Make sure not to change the dictionary while you are working with the names (add,delete). If you do that, you should extract the keys again with slot_dict.keys() to get an updated version.

To get the object references do that:

for name in names:
  object = slot_dict[name]

I hope it helps to understand

Thanks guys! I realized this morning I should have explained my goal in my first post and just now getting to it. Anyway, I am making an inventory bar for my game and using empties as item slots. When adding a new item to the inventory bar I need to check the empties for child items in order (check itemslot01 if yes then check itemslot02 for child…) When printing my list I realized it was all out of order so I was trying to sort it so I could check the slots in proper order.

I am sitting down now to implement your suggestions but it looks like it should work for what I’m doing. Thanks again!!

EDIT: Worked great and since I’m not removing or adding slots no worries there