Manoj Suryawanshi
Manoj Suryawanshi

Reputation: 882

Use list values as dictionary keys as key val

I am creating a dictionary using a list value as a key. Now I want to get dictionary keys in same order as list values. Please find the code below:

dict = {}

category_list = [u'Customer', u'Consumers', u'OpenERP Partners', u'Basic Partner', u'Retailers', u'Supplier']

for category in category_list:
    dict[category] = 0.0

print "dict--->", dict 

I am getting a output as:

dict--->{u'Customer': 0.0, u'Consumers': 0.0, u'Basic Partner': 0.0, u'Supplier': 0.0, u'Retailers': 0.0, u'OpenERP Partners': 0.0}

But I want dictionary keys in the same order as list is defined. i.e. output should be like:

 dict--->{u'Customer': 0.0, u'Consumers': 0.0, u'OpenERP Partners': 0.0, u'Basic Partner': 0.0,  u'Retailers': 0.0, u'Supplier': 0.0,}

Upvotes: 1

Views: 352

Answers (2)

Marius
Marius

Reputation: 60160

You could always just use your original list to print the dictionary in the right order, although I'm not sure what you're planning to do with the dictionary eventuallly.

for categ in category_list:
     print categ, dict[categ]

Upvotes: 1

srgerg
srgerg

Reputation: 19339

You need to use an OrderedDict. For example:

>>> import collections
>>> d = collections.OrderedDict()
>>> category_list = [u'Customer', u'Consumers', u'OpenERP Partners', u'Basic Partner', u'Retailers', u'Supplier']
>>> for category in category_list:
...   d[category] = 0.0
... 
>>> print d
OrderedDict([(u'Customer', 0.0), (u'Consumers', 0.0), (u'OpenERP Partners', 0.0), (u'Basic Partner', 0.0), (u'Retailers', 0.0), (u'Supplier', 0.0)])

Also, dict is already used in python to refer to the dict class, so you should avoid using it as a variable name.

Upvotes: 5

Related Questions