如何使用索引更新字典

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

How to update dictionary with indexes

问题

我有一个列表和字典

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

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

  1. list_1 = ['item 0', 'item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6']
  2. dic_1 = {'item 3': 'val 3', 'item 1': 'val 1', 'item 5': 'val 5'}

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

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

我期望的结果是:

  1. 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

  1. list_1 = ['item 0', 'item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6']
  2. 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

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

I expected result:

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

Please help me to do this

答案1

得分: 7

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

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

将得到:

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

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

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

which gives:

  1. {3: 'val 3', 1: 'val 1', 5: 'val 5'}

答案2

得分: 3

你可以这样做。

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

You can do it like this.

  1. result = {}
  2. for key,value in dic_1.items():
  3. if key in list_1:
  4. 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:

确定