问题
What I'm trying to do is get 3 values from a key into separate variables. Currently I'm doing it like this:
for key in names:
posX = names[key][0]
posY = names[key][1]
posZ = names[key][2]
This doesn't seem very intuitive to me even though it works. I've also tried doing this:
for key, value in names:
location = value
Unfortunately, this gives me a single object (which is what I expected), but I need the individual values assigned to the key. Thanks and apologize for my newness to Python.
Update Apologies for not specifying where I was getting my values from. Here is how I'm doing it for the first example.
names = {}
for name in objectNames:
cmds.select(name)
location = cmds.xform(q=True, ws=True, t=True)
names[name] = location
回答1:
It's not unintuitive at all.
The only way to store "multiple values" for a given key in a dictionary is to store some sort of container object as the value, such as a list or tuple. You can access a list or tuple by subscripting it, as you do in your first example.
The only problem with your example is that it's the ugly and inconvenient way to access such a container when it's being used in this way. Try it like this, and you'll probably be much happier:
>>> alist = [1, 2, 3]
>>> one, two, three = alist
>>> one
1
>>> two
2
>>> three
3
>>>
Thus your second example could instead be:
for key, value in names.items():
posX, posY, posZ = value
As FabienAndre points out in a comment below, there's also the more convenient syntax I'd entirely forgotten about, for key,(posX,posY,posZ) in names.items():
.
You don't specify where you're getting these values from, but if they're coming from code you have control over, and you can depend on using Python 2.6 or later, you might also look into named tuples. Then you could provide a named tuple as the dict value, and use the syntax pos.x
, pos.y
, etc. to access the values:
for name, pos in names.items():
doSomethingWith(pos.x)
doSomethingElseWith(pos.x, pos.y, pos.z)
回答2:
If you don't mind an external dependency, you could include Werkzeug's MultiDict:
A MultiDict is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers.
>>> d = MultiDict([('a', 'b'), ('a', 'c')])
>>> d
MultiDict([('a', 'b'), ('a', 'c')])
>>> d['a']
'b'
>>> d.getlist('a')
['b', 'c']
>>> 'a' in d
True
Another way to store multiple values for a key is to use a container type, like a list
, a set
or a tuple
.
回答3:
Looking at your code, working with position/location variables, you could also unify the X, Y and Z position into a common type, for example using named tuples:
from collections import namedtuple
Position = namedtuple("Position", "x, y, z")
locations = {
"chair": Position(1, 2, 5.3),
"table": Position(5, 3.732, 6),
"lamp": Position(4.4, 7.2, 2)
}
print "Chair X location: ", locations["chair"].x
Just a suggestion, though.
来源:https://stackoverflow.com/questions/3644409/multiple-values-for-key-in-dictionary-in-python