英文:
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()}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论