Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding list as dictionary value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading