Niklas R
Niklas R

Reputation: 16870

Can I be sure about the order in a dictionary?

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?

Upvotes: 3

Views: 95

Answers (4)

Duncan
Duncan

Reputation: 95652

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.

Upvotes: 1

Craig Citro
Craig Citro

Reputation: 6625

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

Upvotes: 6

John La Rooy
John La Rooy

Reputation: 304147

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

Upvotes: 6

glglgl
glglgl

Reputation: 91017

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.

Upvotes: 3

Related Questions