Appending values to dictionary/list

时间:2018-03-22 23:22:38

标签: python-3.x list dictionary for-loop

I have a mylist = [[a,b,c,d],...[]] with 650 lists inside. I am trying to insert this into a relational database with dictionaries. I have the following code:

for i in mylist:
    if len(i) == 4: 
       cve_ent = {'state':[], 'muni':[], 'area':[]}
       cve_ent['state'].append(i[1])
       cve_ent['muni'].append(i[2])
       cve_ent['area'].append(i[3])

However this code just yields the last list in mylist in the dictionary. I have tried also with a counter and a while loop but I cannot make it run.

I do not know if this is the fastest way to store the data, what I will do is compare the values of the first and second keys with other tables to multiply the values of the third key.

1 个答案:

答案 0 :(得分:0)

First of all, pull

cve_ent = {'state':[], 'muni':[], 'area':[]}

out of your for loop. That will solve issues with re-writing things.