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

How to update dictionary with indexes

I have a list and dictionary

I need to update my dictionary depend on the list

If dictionary has key existing on list on same name, so then I need to get the index of the list item
and set it as a key of the same dictionary item

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

 list_1 = ['item 0', 'item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6']

 dic_1 = {'item 3': 'val 3', 'item 1': 'val 1', 'item 5': 'val 5'}

I tried it with this coding part but couldn’t get which I expected result

for index, column in enumerate(list_1):
    if column in list(dic_1.keys()):
        print(f"header : {index} - {column} | align : {list(dic_1).index(column)} -  {dic_1[column]}")
        dic_1[column[0]] = dic_1.pop(list(dic_1.keys())[0])
    else:
        pass

I expected result:

 dic_1 = {3: 'val 3', 1: 'val 1', 5: 'val 5'}

Please help me to do this

>Solution :

You can’t edit a dictionary in that way. Use:

new_dic = {list_1.index(x):y for x, y in dic_1.items()}

which gives:

{3: 'val 3', 1: 'val 1', 5: 'val 5'}
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