简体   繁体   中英

how to append item to dictionary value is a list python

I have xlsx file like this

travel_df = pd.read_excel('../Data/TopMart.xlsx')
data = travel_df.to_dict('records')

the data look like this

parent_name_1      parent_name_2      parent_name_3
     A1                  B1                 C1
     A2                  B2                 C2
     A3                  B3                 C3
     A4                  B4                 C4

I want to make dict like this from that:

cat = {
    A1 : [B1, C1],
    A2 : [B2, C2],
    A3 : [B3, C3],
    A4 : [B4, C4],
}

what is the best way to do that

  1. Set parent_name_1 as index.
  2. Transpose the dataframe
  3. Convert it to dict ignoring the new index after the transpose parent_1, parent_2, parent_3 using to_dict(orient="list") .

cat = travel_df.set_index("parent_name_1").T.to_dict(orient="list")

Maybe there is a better function to do this directly, but I couldn't find it... But the df.to_dict('split') gets something that helps, and is easy enough to finish the way. This is what split gives us:

{'index': [0, 1, 2, 3],
 'columns': ['parent_name_1', 'parent_name_2', 'parent_name_3'],
 'data': [['A1', 'B1', 'C1'],
  ['A2', 'B2', 'C2'],
  ['A3', 'B3', 'C3'],
  ['A4', 'B4', 'C4']]}

The data item here sort of has what we want, sort of...

l = df.to_dict('split')['data']
cat = dict()
for n in l:
    cat.update({n[0]:[n[1],n[2]]})

At the end of that, cat looks just how (I think) you want.

import pandas as pd

my_data = pd.DataFrame({
    'A': ['A1', 'A2', 'A3', 'A4'],
    'B': ['B1', 'B2', 'B3', 'B4'],
    'C': ['C1', 'C2', 'C3', 'C4']
})

result = my_data.set_index('A').to_dict('index')

{key: list(value.values()) for key, value in result.items()}

Result Object:

{'A1': {'B': 'B1', 'C': 'C1'},
 'A2': {'B': 'B2', 'C': 'C2'},
 'A3': {'B': 'B3', 'C': 'C3'},
 'A4': {'B': 'B4', 'C': 'C4'}}

Final Output

{'A1': ['B1', 'C1'],
 'A2': ['B2', 'C2'],
 'A3': ['B3', 'C3'],
 'A4': ['B4', 'C4']}

I don't know if it is the best way, but you can try:

import pandas

if __name__ == "__main__":
    xls = pandas.read_excel("test.xls")
    data = {xls.iloc[i][0]: list(xls.iloc[i][1:].values) for i in range(len(xls))}

Assuming that your first column has unique keys.

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