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

In Python can you add elements from a list to the values of a dictionary?

I am trying to add the elements of a list of list to the values of a dictionary.

I have created a list with elements from a file that looks like this:

list_of_lists = [[966], [1513, 2410], [2964, 1520, 604]....] 

I am trying to add this list to a dictionary that I have made to look like this:

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

{'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739, 
12011], 'Yakima': ['WA', 4660, 12051, 49826]....]

I have tried the following code:

 x = 1
 for x in d2.values():
     d2.append(list_of_list)
 print(d2)

I am not even sure that this is something that is possible, but I am trying to get the dictionary to be:

{'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739, 
12011, [966]], 'Yakima': ['WA', 4660, 12051, 49826, [1513, 2410]]....]

>Solution :

I know there are more ways to do that, But I think this is more readable and understandable code.

list_of_lists = [[966], [1513, 2410], [2964, 1520, 604]] 

dict_ = {'Youngstown': ['OH', 4110, 8065, 115436], 'Yankton': ['SD', 4288, 9739, 
12011], 'Yakima': ['WA', 4660, 12051, 49826]}

i = 0
# list(dict_.items())[1:] is the list of all keys and values except first one.
for key,value in list(dict_.items())[1:]:
    dict_[key] = value+[list_of_lists[i]]
    i+=1
print(dict_)

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