简体   繁体   中英

How to convert a dict of dicts to a dict of tuples in python

I read an excel distance matrix and generated a dataframe:

df = pd.read_excel(xlsx, "Dem_Prod")

   Merc\Prod    1   2   3   4
0   1          80   85  300 6
1   2         270   160 400 7
2   3         250   130 350 4
3   4         160   60  200 3
4   5         180   40  150 5

Hen I created a dict

d = df.set_index('Merc\Prod').T.to_dict()

{1: {1: 80, 2: 85, 3: 300, 4: 6}, 2: {1: 270, 2: 160, 3: 400, 4: 7}, 3: {1: 250, 2: 130, 3: 350, 4: 4}, 4: {1: 160, 2: 60, 3: 200, 4: 3}, 5: {1: 180, 2: 40, 3: 150, 4: 5}}

But I want a dict of tuples

{(1,1):80, (1,2):85, (1,3):300, (1,4):6, (2,1):270, (2,2):160, (2,3):400, (2,4):7, (3,1):250, (3,2):130, (3,3):350, (3,4):4, (4,1):160, (4,2):60, (4,3):200, (4,4):3, (5,1):180, (5,2):40, (5,3):150, (5,4):5 }

You can do stack with set_index

d=df.set_index('Merc\Prod').stack().to_dict()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM