質問

Can I be sure about the order in a Python dictionary?

The function op.GetTangent(id) returns a dictionary containing two values associated with 'vl' and 'vr'. I want to unpack it the lazy way.

vr, vl = op.GetTangent(id).values()

Can I be sure that vr and vl have the correct value or can there be a case where they're exchanged?

役に立ちましたか?

解決

vr, vl = map(op.GetTangent(id).get, ('vr', 'vl'))

他のヒント

No, you should never depend on the order of the entries returned by the values method. You have several easy options:

  • Call sorted on the resulting list (if the values can be sorted)
  • Call sorted on the items and pull out the values
  • Use a collections.OrderedDict

No, never.

Instead do

getbyname = lambda d, *kk: [d[k] for k in kk]

and use it as

vr, vl = getbyname(op.GetTangent(id), 'vr', 'vl')

or just do

d = op.GetTangent(id)
vr, vl = [d[i] for i in ('vr', 'vl')]

if you need it only once.

Just for the complete avoidance of any doubt whatsoever, actual output on my system:

C:\Python32>python -c "print({'vr':1, 'vl':2})"
{'vr': 1, 'vl': 2}

C:\Python32>python -c "print({'vr':1, 'vl':2})"
{'vl': 2, 'vr': 1}

That is running Python 3.2.3 with PYTHONHASHSEED set to 'random' and different runs of identical code have different orders of items in the dictionary.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top