0

I'm working on small project using Python i try to refactor my pd.read_excel() result but i get only the last row in my data variable:

this is my code :

@action(methods=['post'], detail=False)
def bulkImport(self, request, pk=None):
    file_uploaded = request.FILES.get('file')
    context = pd.read_excel(file_uploaded, engine='openpyxl')
    data = {}
    for column in context:
        for b in context[column].tolist():
            data[column] = b
            
    print(data)

Native read_excel() result :

{
    "name": [
        "amine",
        "bill"
    ],
    "company": [
        "bouhaddi",
        "microsoft"
    ],
    "email": [
        "[email protected]",
        "[email protected]"
    ],
    "phone": [
        43822510594,
        559485556555
    ],
    "adress": [
        "3820 albert st",
        "new york"
    ]
}

Expected Result :

{
    'name' : 'value',
    'phone' : 'value',
    'email' : 'value',
    'company' : 'value',
    'adress' : 'value',
},
{
    'name' : 'value',
    'phone' : 'value',
    'email' : 'value',
    'company' : 'value',
    'adress' : 'value',
}
    

1 Answer 1

1
context={
    "name": [
        "amine",
        "bill"
    ],
    "company": [
        "bouhaddi",
        "microsoft"
    ],
    "email": [
        "[email protected]",
        "[email protected]"
    ],
    "phone": [
        43822510594,
        559485556555
    ],
    "adress": [
        "3820 albert st",
        "new york"
    ]
}

data=[{k:v[i]  for k,v in context.items() } for i in range(2) ]

Output:

[{'name': 'amine',
  'company': 'bouhaddi',
  'email': '[email protected]',
  'phone': 43822510594,
  'adress': '3820 albert st'},
 {'name': 'bill',
  'company': 'microsoft',
  'email': '[email protected]',
  'phone': 559485556555,
  'adress': 'new york'}]

Using list comprehension and dictionary comprehension can give you the two dicts within a list

Sign up to request clarification or add additional context in comments.

13 Comments

please can you give me a real example :) using my function if possible
data is empty when i print
I modified your data variable because there are many unknowns for me like columns...
i used your code but there is no result in data :(
print(data) is empty
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.