0

I have a list of dictionaries (old_list) and I am trying to reassign some of keys to be the values and some of the values to be the keys. The back story is I'm Using python docx, I was looping through docx files in a folder and extracting the data in a table from all the docx files in that folder. The data loads as a list of dictionaries, but assigns some of the keys as values and some of the values as keys. I would like the old list to look something like(see new_list).It seems that the structure of the table documents is the reason the text is loading in this way. I do not own the documents so I cannot change the structure of the tables. So my only option is to fix the list of dictionaries. is there a way to do so?

old_list = [{"A":"B" , "C":"D"},{"D":"E" , "F":"G"}]

new_list = [{"A":"C" , "B":"D"},{"D":"F" , "E":"G"}]

for reference below is the code I use to extract the data from the document files

import Docx

data_t = []
def getTable(filename): 
    document = Document(filename)
    table = document.tables[0]
    keys = None
    for i, row in enumerate(table.rows): 
        text = (cell.text for cell in row.cells) 
        if i == 0: 
            keys = tuple(text) 
            continue 
        row_data = dict(zip(keys, text)) 
        data_t.append(row_data) 

path = (r'C:\Users\OyooP\Desktop\auto1*.docx')
files=glob.glob(path) 
table_list = [] 
for f in files: 
    tbl_corpus = getTable(f) 
    table_list.append(tbl_corpus) 

corpus_list[0] 
data_t 
Philo
  • 31
  • 1
  • 5
  • https://stackoverflow.com/questions/483666/reverse-invert-a-dictionary-mapping but be careful as you can have duplicate values, but not duplicate keys. -- Oh sorry, reading your code this isn't quite the same. – Kenny Ostrom Dec 12 '20 at 15:19
  • Can you skip the docx part and just show the actual text you have to work with? Your zip looks good at first glance, and I have to be away from the computer for a while now. – Kenny Ostrom Dec 12 '20 at 15:27

1 Answers1

0

Try this.

old_list =  [{"A":"B" , "C":"D"},{"D":"E" , "F":"G"}]

for i, (a,b) in enumerate(old_list):
    _temp = old_list[i][a] 
    old_list[i][a] = b
    old_list[i][_temp] = old_list[i][b]
    del old_list[i][b]

Output:

[{'A': 'C', 'B': 'D'}, {'D': 'F', 'E': 'G'}]
Rauf Bhat
  • 116
  • 4