How to update dictionary with indexes

Question:

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

 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

Asked By: sonny

||

Answers:

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'}
Answered By: user19077881

You can do it like this.

result = {}
for key,value in dic_1.items():
    if key in list_1:
        result[list_1.index(key)]=value
Answered By: salmanwahed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.