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.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
Use list() to create a dictionary with lists as the values. Use the dictionary assignment syntax dict[key] = value with value as list() to assign lists to the values of dict .
A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.
Try this:
from collections import OrderedDict
keys=['blk','pri','ani']
vals1=['blocking','primary','anim']
vals2=['S1','S2','S3']
print OrderedDict(zip(keys, zip(vals1, vals2)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With