Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to deep copy a list of dictionaries

I have a list whose each element is a dictionary. Each element looks something like this

{'CELL': <Cell SOW16007.2.AC7>, 'COUNT': 2, 'NAMELIST': [], 'NAME': u'', 'LEVEL': u'SSE'}

I need to make a backup of this list.Normal assignment or using shallow copy is not option i can use as i will making changes to the original. But when i use deepcopy backUpNames=deepcopy(oldNames) I'm getting an error :

TypeError: unhashable type: 'array.array'

What wrong am i doing here? How can i solve this?

This is a not a duplicate question as I have already used deepcopy, problem i am facing is with the error deepcopy is throwing.

Minimal Code:

Using openpxl i iterate the sheet and append the values to a list

wb=openpyxl.load_workbook(sys.argv[3],data_only=True)
_ts=wb.active 
oldNames.append({'NAME':_ts['G7'].value,'LEVEL':_ts['H7'].value,'CELL':_ts['F7'],'COUNT':0,'NAMELIST':[]})
backUpNames=deepcopy(oldNames)#error occurring here

Thank You

like image 323
Vinod Pn Avatar asked Dec 16 '16 06:12

Vinod Pn


1 Answers

import copy
list = [{'a':1,'b':2},{'c':3,'d':4}]
cpy_list = []
for li in list:
    d2 = copy.deepcopy(li)
    cpy_list.append(d2)
print cpy_list
like image 163
dsingh Avatar answered Sep 20 '22 06:09

dsingh