Hi want to have a ordered dictionary with keys having list of values.
from below code i could able to get a dictionary with list of keys but ordered of insertion is missing.
from collections import defaultdict
keys=['blk','pri','ani']
vals1=['blocking','primary','anim']
vals2=['S1','S2','S3']
dic = defaultdict(list)
i=0
for key in keys:
dic[key].append(vals1[i])
dic[key].append(vals2[i])
i += 1
print dic
i get the following result
defaultdict(<type 'list'>, {'pri': ['primary', 'S2'], 'ani': ['anim', 'S3'], 'blk': ['blocking', 'S1']})
here i lost insert order.
I know defaultdict object in Python are unordered by definition.
And i know we need to Use OrderedDict if you need the order in which values were inserted (it’s available in Python 2.7 and 3.x)
So changed my code as below
from below code i could able to get what i need.
from collections import defaultdict,OrderedDict
keys=['blk','pri','ani']
vals1=['blocking','primary','anim']
vals2=['S1','S2','S3']
dic = OrderedDict(defaultdict(list))
i=0
for key in keys:
dic[key].append(vals1[i])
dic[key].append(vals2[i])
i += 1
print dic
and now i get the below error
Traceback (most recent call last):
File "Dict.py", line 18, in <module>
dic[key].append(vals1[i])
KeyError: 'blk'
Can any one tell me how to get what i am trying.
If you really want the “Ordered” and “default” behavior, I think I would create a custom dictionary class to handle everything for me:
This will behave more like the
defaultdictthan the other solutions, but it will retain it’s order, and it really isn’t a whole lot of code :). Finally, you could even override__init__to allow the user to pass any “factory” they wanted (rather than hard-codinglist). I’ll leave that as an exercise for the interested reader. Python is so cool.