remove brackets from the values stored in a dictionary

Asked

Viewed 243 times

0

When trying to use an excel spreadsheet as a data source for my DOCX-TEMPLATE, the dictionary I am generating is storing the values with brackets, and these and brackets are appearing in the final text that is generated in DOCX by Docx-Template. To simplify, I used an excel table that contains the following data:

name    birth      gender
 Felipe   07/04/1988   male 

My code is as follows:

import pandas as pd
from docxtpl import DocxTemplate

file_path = 'teste.xlsx'
df = pd.read_excel(file_path, encoding='utf-8')
data = df.to_dict(orient= 'list')

doc = DocxTemplate("modelo.docx")
context = data
doc.render(context)
doc.save("generated_doc.docx")

To simplify, my ".docx template" contains the following text: My name is {{ name }}, i am {{ gender }} and i was born in {{ birth }}.

The Output generated in "generated_doc.docx" is: My name is ['felipe], i am ['male'] and i was born in [Timestamp('1988-04-07 00:00:00')].

If I give a print(data) to check my dictionary, the result is {'name': ['felipe'], 'birth': [Timestamp('1988-04-07 00:00:00')], 'gender': ['male']} . If I execute the command data['name'] = 'felipe' , my dictionary will stay : {'name': 'felipe', 'birth': [Timestamp('1988-04-07 00:00:00')], 'gender': ['male']} and it will work. Therefore, I need to figure out a way to change all the stored values so as to remove their brackets. Or else, is there any way to store them without the clasps? I read the documentation of read_excel() and to_dict(), but could not solve the problem.

1 answer

1


The fact that your dictionary is like this: {'name': ['felipe'], 'birth': [Timestamp('1988-04-07 00:00:00')], 'gender': ['male']} indicates that each value in the dictionary is a list, with a single element.

So "remove square brackets" is actually creating another dictionary (or updating it), so that all lists of a single element are no longer lists and become elements.

One of the ways to create a new dictionary is to use a "Dict comprehension" - an expression with a for in the same line - Dict-comprehension saves about 2 or 3 lines of program - so to make it easier to understand, I’ll do "in full" first - then in the form of Dict comprehension:

novo = {}
for chave, valor in data.items():
    if isinstance(valor, list):
        novo[chave] = valor[0]  # (pega o primeiro elemento da lista)
    else:
        novo[chave] = valor

data = novo

With the use of "Dict comprehension" this same excerpt can be written as:


data = {chave: valor[0] if isinstance(valor, list) else valor for chave, valor in data.items()} 

  • Thank you jsbueno. This is because I used the function to_dict(orient= 'list') in my Dataframe, right? She was the only one who seemed to format the content the best way for Docx to read. Anyway, you solved my problem !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.