Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign list of values to a key using OrderedDict in python

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.

like image 376
Rao Avatar asked Nov 07 '12 07:11

Rao


People also ask

How do you add multiple values to a key in Python?

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.

How do you assign a value to a dictionary in a list?

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 .

Can we give list as a key in dictionary Python?

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.


1 Answers

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)))
like image 172
Artsiom Rudzenka Avatar answered Oct 13 '22 11:10

Artsiom Rudzenka