如何为python字典创建“catch all”键?

2024-04-26 20:22:28 发布

您现在位置:Python中文网/ 问答频道 /正文

对于python字典,是否可以创建一个当请求的键不存在时字典将默认使用的键?在

编辑:我不明白下面和上面提到的解决方案是如何解决这个问题的

如果我问dictionary['xxx'],其中xxx不是已知值或变量,它可以是任何字符串,我如何使用dictionary['key']和字典.get('key','defaultvalue')

编辑2:

spouse={John:Joan, Bob:Marry}

当我要求配偶时,我应该“不结婚” 同样的道理也适用于任何一个男人的鬃毛,它不是字典里的一个键

我希望现在更清楚了

defaultdict注释似乎是唯一有用的


Tags: key字符串编辑getdictionary字典解决方案john
1条回答
网友
1楼 · 发布于 2024-04-26 20:22:28

调用可能有或没有给定键的字典时,可以设置如下默认值:

>>> my_dict = {'color':'red', 'size':'2'}
>>> my_dict.setdefault('style', 'round')
'round'

>>> my_dict = {'color':'red', 'size':'2', 'style':'square'}
>>> my_dict.setdefault('style', 'round')
'square'

关于您编辑的问题:

Edit2:

^{pr2}$

when I ask for spouse[Dan] I should get "not married" same should go for any male name that comes to user's mind and it is not a key in the dictionary

你可以这样做:

>>> spouse = {}
>>> spouse['Jim']='Lucy'
>>> spouse['Alex']='Sandra'
>>> users = ['Dan', 'Phil','Jim','Alex']
>>> for i in range(len(users)):
>>>     s = spouse.setdefault(users[i], 0)
>>>     if s == 0:
>>>         print "%s is not married" % users[i]
>>>     else:
>>>         print "%s's spouse is %s" % (users[i],s)

'Dan is not married'
'Phil is not married'
'Jim's spouse is Lucy'
'Alex's spouse is Sandra'

相关问题 更多 >