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
>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'}