字典弹出

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

Dictionary popping

问题

  1. 我尝试在字典thisdict中如果键不在其中则弹出键但是我一直收到键错误
  2. ```python
  3. userList = [User(id='1', username='bob'), User(id='2', username='john')]
  4. players = {}
  5. players['1'] = 'bob'
  6. players['4534509345ffgdfgd'] = 'caleb'
  7. print(players)
  8. # 遍历字典的项
  9. for key, value in list(players.items()):
  10. found = False
  11. # 检查是否在userList中找到匹配项
  12. for user in userList:
  13. if user.id == key and user.username == value:
  14. found = True
  15. break
  16. # 如果没有找到匹配项,则删除该项
  17. if not found:
  18. players.pop(key)
  19. print(players)

因为Caleb不在thisdict中,所以应该从players中删除。Player具有属性username和id。

英文:

I'm trying to pop they key if it is not in dictionary thisdict but I keep getting a key error

  1. userList = [User(id='1', username='bob'), User(id='2', username='john')]
  2. players = {}
  3. players['1'] = 'bob'
  4. players['4534509345ffgdfgd'] = 'caleb'
  5. print(players)
  6. for y in players.items():
  7. if y not in userList:
  8. players.pop(y)
  9. print(players)

Caleb should be removed from players because he is not present in thisdict. How do I do this please? Player does have attribute username and id

答案1

得分: 1

假设User对象具有可以访问的username属性,并且您想要修改players字典。

  1. # 生成可接受的名称集合 *一次*
  2. player_names = {player.username for player in thisdict}
  3. filtered_players = {
  4. key: value
  5. for key, value in players.items()
  6. if value.username in player_names
  7. }

这将生成一个的字典,不会修改原始的players字典。

英文:

Assuming User objects have an attribute username that can be accessed and that you want to modify the players dictionary.

  1. # Generating a set of acceptable names *once*
  2. player_names = {player.username for player in thisdict}
  3. filtered_players = {
  4. key: value
  5. for key: value in players.items()
  6. if value.username in player_names
  7. }

This generates a new dictionary and does not modify the original players dictionary.

答案2

得分: 0

{k:v for k,v in players.items() if v in thisdict.values()}:这是一个一行代码,可以实现你想要的功能。

英文:

Here is a one liner to do what you want :

  1. {k:v for k,v in players.items() if v in thisdict.values()}

huangapple
  • 本文由 发表于 2023年6月2日 04:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385633.html
匿名

发表评论

匿名网友

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

确定