'Prioritization data from data frame with dictionary using pandas

I have a problem with my db, here is a sample frame that I am working on which describes number of toys (Qty) that I need to relocate to specific factory (To) and number of them which already is in other factories (A,B,C,D,E,F,G):

enter image description here

And I have created a dictionary which prioritize the destinations between this factories in format

'to': ['first choice', 'second choice'...]:

d = {'A': ['F', 'E', 'D', 'B'],
     'B': ['E', 'F'],
     'C': ['A', 'B'],
     'D': ['F', 'C', 'E', 'B', 'A'],
     'E': ['F', 'C', 'D', 'B', 'A'],
     'F': ['F', 'C', 'D', 'B', 'A'],
     'G': ['F', 'C', 'D', 'B', 'A']}

Now I wanted to pick toys from factory basing on my priority dict and create a new column which will show name of the factory.\

E.g. if I look at the toy with id 3 I want 20 of them to the factory A and as we can see there is a lack of them in factory F so I want to take 2 of them from factory F and rest (18) from the next one from my dictionary so from factory E.

Simple output:

enter image description here

Here is this tables in text to copy it to your excel/txt files.

ID  To  Qty A   B   C   D   E   F   G
1   A   6   0   0   0   0   0   302 0
2   A   4   0   625 0   0   357 0   0
3   A   20  0   0   0   318 154 2   0
4   B   12  0   0   0   0   0   473 0
5   C   13  0   0   0   0   0   6713 0
6   A   3   0   0   0   0   0   37  0
7   A   2   0   0   0   0   0   105 0
8   D   51  0   0   0   0   0   6782 0
9   B   2   0   0   0   0   0   946 0


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source