Ash Sharma
Ash Sharma

Reputation: 468

Behavior of OrderdDict

I was answering one of the questions on SO and I stumbled upon this behavior of OrderedDict, which I could not explain. It goes as follows You have a dict that looks like this:

exmpl  = OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0)), (43, ('A4', float('nan')))])

The goal is to remove the dictionary entries which has nan in it, which can be accomplished in the following ways:

  1. By use of for loop

    for k,v in dict_cg.items():
      if np.isnan(v[1]):
         exmpl.pop(k)
    print exmpl
    

    and the output will be

     OrderedDict([(30, ('A1', 55.0)), (31, ('A2', 125.0)), (32, ('A3', 180.0))])
    
  2. Through dictionary comprehension method (while defining it as an OrderedDict) as follows

    exmpl = OrderedDict({k:v for k, v in dict_cg.items() if not np.isnan(v[1])})
    print exmpl
    

which returns

  OrderedDict([(32, ('A3', 180.0)), (30, ('A1', 55.0)), (31, ('A2', 125.0))])

Can someone educated me, as to why the dictionary jumbled in the second case turns up jumbled.?

Upvotes: 1

Views: 37

Answers (2)

Edward Minnix
Edward Minnix

Reputation: 2947

Like @timgeb mentioned, in Python versions before 3.6, dictionary order is effectively random. If you want to still use a comprehension in Python 3.5 and below, you can use a list comprehension of tuples instead:

OrderedDict([(k, v) for k, v in dict_cg.items() if not np.isnan(v[1])])

Upvotes: 2

timgeb
timgeb

Reputation: 78780

Because you are creating an ordinary dictionary with a dictionary comprehension, which has arbitrary order, which you pass to the OrderedDict constructor afterwards.

Upvotes: 4

Related Questions