字典弹出

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

Dictionary popping

问题

我尝试在字典thisdict中如果键不在其中则弹出键但是我一直收到键错误

```python
userList = [User(id='1', username='bob'), User(id='2', username='john')]
players = {}
players['1'] = 'bob'
players['4534509345ffgdfgd'] = 'caleb'

print(players)

# 遍历字典的项
for key, value in list(players.items()):
    found = False
    
    # 检查是否在userList中找到匹配项
    for user in userList:
        if user.id == key and user.username == value:
            found = True
            break
    
    # 如果没有找到匹配项,则删除该项
    if not found:
        players.pop(key)

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

userList = [User(id='1', username='bob'), User(id='2', username='john')]
players = {}
players['1'] = 'bob'
players['4534509345ffgdfgd'] = 'caleb'

print(players)

for y in players.items():
    if y not in userList:
      players.pop(y)
      
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字典。

# 生成可接受的名称集合 *一次*
player_names = {player.username for player in thisdict}

filtered_players = {
  key: value 
  for key, value in players.items()
  if value.username in player_names
}

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

英文:

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

# Generating a set of acceptable names *once*
player_names = {player.username for player in thisdict}

filtered_players = {
  key: value 
  for key: value in players.items()
  if value.username in player_names
}

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 :

{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:

确定