Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a python dict in order of key values

I have a python dictionary that looks like this:

In[1]: dict_concentration Out[2] : {0: 0.19849878712984576, 5000: 0.093917341754771386, 10000: 0.075060643507712022, 20000: 0.06673074282575861, 30000: 0.057119318961966224, 50000: 0.046134834546203485, 100000: 0.032495766396631424, 200000: 0.018536317451599615, 500000: 0.0059499290585381479} 

They keys are type int, the values are type float64. Unfortunately, when I try to plot this with lines, matplotlib connects the wrong points (plot attached). How can I make it connect lines in order of the key values? enter image description here

like image 575
DJname Avatar asked May 17 '16 02:05

DJname


People also ask

Does order of keys matter in dictionary Python?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.

How is Python dict ordered?

Python OrderedDict is a dict subclass that maintains the items insertion order. When we iterate over an OrderedDict, items are returned in the order they were inserted. A regular dictionary doesn't track the insertion order. So when iterating over it, items are returned in an arbitrary order.


1 Answers

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt  lists = sorted(d.items()) # sorted by key, return a list of tuples  x, y = zip(*lists) # unpack a list of pairs into two tuples  plt.plot(x, y) plt.show() 

Here is the result. enter image description here

like image 115
SparkAndShine Avatar answered Sep 21 '22 17:09

SparkAndShine