Issue
I am trying to transform my dictionary to a "look up dictionary" with multiindexes.
I have the following dictionary where the current keys are the period:
{8: {'FlightName': ['Flightname612'],
'Flight_idx': array([268]),
'Baggage': array([149]),
'infeed_idx': [1]},
9: {'FlightName': ['Flightname612'],
'Flight_idx': array([268]),
'Baggage': array([149]),
'infeed_idx': [2]},
10: {'FlightName': ['Flightname353', 'Flightname394', 'Flightname612'],
'Flight_idx': array([ 9, 50, 268]),
'Baggage': array([ 21, 1, 149]),
'infeed_idx': [1, 1, 3]},
And I would like a dictionary where I can look up the flight index and the infeed index and it will then return then period. So the expected out:
(flight_idx, infeed_idx)=period
(268,1) = 8
(268,2) = 9
(9,1) = 10
(50,1) = 10
(268,3)=10
I was out trying to solve it using a loooot of loops, but I feel like there is a simple solution, if you know your way around pandas, dictionaries and operations. I hope you can help!
Solution
You can create a dataframe with data as your input dictionary's values and index as its keys.
Then reset_index()
to make a new column for period
and set_index() with [Flight_idx, infeed_idx]
and use that to build a dictionary by using to_dict
.
Code:
df = pd.DataFrame(in_dict.values(), index=in_dict.keys())
out_dict = df.explode(["Flight_idx", "infeed_idx"]).rename_axis("period").reset_index().set_index(
["Flight_idx", "infeed_idx"]
)["period"].to_dict()
print(out_dict):
{(268, 1): 8, (268, 2): 9, (9, 1): 10, (50, 1): 10, (268, 3): 10}
Answered By - SomeDude
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.