I want a dict or tuple I can sort based on attributes of the objects I’m using as arguments for *arg. The way I’ve been trying to do it just gives me AttributeErrors, which leads me to believe I’m doing it weird.
def function(*arg):
items = {}
for thing in arg:
items.update({thing.name:thing})
while True:
for thing in items:
## lots of other code here, basically just a game loop.
## Problem is that the 'turn order' is based on whatever
## Python decides the order of arguments is inside "items".
## I'd like to be able to sort the dict based on each object's
## attributes (ie, highest 'thing.speed' goes first in the while loop)
The problem is when I try to sort “items” based on an attribute of the objects I put into function(), it gives me “AttributeError: ‘str’ object has no attribute ‘attribute'”. Which leads me to believe I’m either unpacking *arg in a lousy way, or I’m trying to do something the wrong way.
while True:
for thing in sorted(items, key=attrgetter('attribute')):
…doesn’t work either, keeps telling me I’m trying to manipulate a ‘str’ object. What am I not doing here?
argalready is atupleyou can sort by an attribute of each item:When you iterate over a
dict, assortedis doing, you just get the keys, not the values. So, if you want to use adict, you need to do:to actually sort the args by an attribute. If you want the keys of the
dictavailable as well (not necessary here because the key is also an attribute of the item), use something like: