Anonymous Entity
Anonymous Entity

Reputation: 3350

How to create this dictionary?

I have a dict object, and a list containing lists, and want to combine the keys of the dict with the lists from the list, however the result always comes out in a (predetermined) mess.

my_dict = {(255,0,0):'red', (0,255,0):'green', (0,0,255):'blue'}
my_list = [[1,2,3], [4,5,6], [7,8,9]]

new_dict = dict(zip(my_dict, mylist))

As you might guess, this is not the actual data, but it's the method I'm using in my program, I'll post the real dict and list if it's necessary.

What I want is for new_dict to be consistent with the ordering of the items as described above. How can we achieve this?

Upvotes: 0

Views: 76

Answers (2)

HennyH
HennyH

Reputation: 7944

You can use an OrderedDict, ordinary dictionaries (dict) are unordered.

from collections import OrderedDict

my_dict = OrderedDict([((255,0,0),'red'), ((0,255,0),'green'), ((0,0,255),'blue')]) #[(key,val),(key2,val2),..]
my_list = [[1,2,3], [4,5,6], [7,8,9]]

new_dict = dict(zip(my_dict, my_list))
print(new_dict)

>>> 
{(0, 0, 255): [7, 8, 9], (0, 255, 0): [4, 5, 6], (255, 0, 0): [1, 2, 3]}

Upvotes: 2

NPE
NPE

Reputation: 500693

dict is inherently unordered. To preserve the ordering, use collections.OrderedDict.

Upvotes: 2

Related Questions