如何使用索引更新字典

huangapple go评论89阅读模式
英文:

How to update dictionary with indexes

问题

我有一个列表和字典

我需要根据列表更新我的字典

如果字典中有与列表中相同名称的键,则我需要获取列表项的索引,并将其设置为相同字典项的键

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

我尝试使用以下代码部分,但无法获得我期望的结果

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

我期望的结果是:

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

请帮助我实现这个。

英文:

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

答案1

得分: 7

你不能以那种方式编辑一个字典。使用:

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

将得到:

{3: 'val 3', 1: 'val 1', 5: 'val 5'}
英文:

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

答案2

得分: 3

你可以这样做。

result = {}
for key, value in dic_1.items():
    if key in list_1:
        result[list_1.index(key)] = value
英文:

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

huangapple
  • 本文由 发表于 2023年3月12日 19:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定