python - Dictionary Keys based on list elements and list values -
i scanning through document making list of each line read in.
i'm saving list called
testlist = []
when i'm done populating list want set value dictionary key based on element of list. thought should this:
testlist = ['informationa', 'informationb', 'lastinfo'] patent_offices = ['european office', 'japan office'] dict_offices[patent_offices[0]] = testlist
or
dict_offices = {'european office' : ['informationa', 'informationb', 'lastinfo'], 'japan office' : ['other list infoa', 'more infob']}
i want later type dict_offices['european office']
, list printed.
but because i'm collecting dynamically read through document erase , reuse testlist
. i've seen after cleared cleared in dictionary's link.
how create dictionary saved can reuse testlist every loop through?
here code:
patent_offices = [] dict_offices = {} office_index = 0 testlist = [] # --- other conditional code not shown if (not patent_match , start_recording): if ( not re.search(r'[=]+', bstring)): #ignore ====== string printstring = fontsstring.encode('ascii', 'ignore') testlist.append(printstring) elif (not start_recording , patent_match): dict_offices[patent_offices[office_index]] = testlist start_recording = true office_index += 1 testlist[:] = []
this dictionary correctly updated , looks want until phone call
testlist[:] = []
line. dictionary goes blank testlist
. understand dictionary linked don't know how not have happen.
lists mutable; multiple references same list see changes create it. testlist[:] = []
means: replace every index in list empty list. because reference same list in different places (including in dictionary values), see alter reflected everywhere.
instead, point testlist
new empty list instead:
testlist = []
the empty piece assignment syntax used should used if want clear contents of list, not when want create new empty list.
>>> foo = [] >>> bar = foo >>> foo.append(1) >>> bar [1] >>> foo bar true >>> foo[:] = [] >>> bar [] >>> foo = ['new', 'list'] >>> bar [] >>> foo bar false
python list dictionary python-2.7
No comments:
Post a Comment