if I have a list of list, for ex
l=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
and a dictionary whose value is of dictionary type itself, for ex
d={"id1":{"A": "", "C": "", "G": "", "T": ""},"id2":{"A":"","C":"","G":"","T":""},
"id3":{"A": "", "C": "", "G": "", "T": ""},"id4":{"A": "", "C": "", "G": "", "T": ""}}
I want loop through the list and each item to the corresponding key in d, output would be like
d={"id1":{"A": "1", "C": "2", "G": "3", "T": "4"},"id2":{"A":"5","C":"6","G":"7","T":"8"},
"id3":{"A": "9", "C": "10", "G": "11", "T": "12"},"id4":{"A": "13", "C": "14", "G": "15", "T": "16"}}
but instead it gives me the following
{'id1': {'A': 15, 'C': 15, 'G': 15, 'T': 15}, 'id2': {'A': 15, 'C': 15, 'G': 15, 'T': 15}, 'id3': {'A': 15, 'C': 15, 'G': 15, 'T': 15}, 'id4': {'A': 15, 'C': 15, 'G': 15, 'T': 15}}
my code so far
for k,v in d.items():
for sub_k,sub_value in v.items():
for i in range(len(l)):
for j in range(len(l[i])):
d[k][sub_k]=l[i][j]
>Solution :
The issue with your code is that you iterate twice on each level of dict, and so, the results you see are the ones of the last iteration. You can fix your code by doing:
for i, (k,v) in enumerate(d.items()):
for j, (sub_k,sub_value) in enumerate(v.items()):
d[k][sub_k]=str(l[i][j]) # adding str() allows to change the int to a str
enumerate allows you to iterate on your dict (k, v for instance) and to have access to the index (i for instance)