Ram*_*amy 20 python dictionary
python字典的默认行为是在字典中创建新密钥(如果该密钥尚不存在).例如:
d = {}
d['did not exist before'] = 'now it does'
Run Code Online (Sandbox Code Playgroud)
对于大多数用途来说,这一切都很好,但是如果键不在字典中,我希望python什么也不做.在我的情况下:
for x in exceptions:
if masterlist.has_key(x):
masterlist[x] = False
Run Code Online (Sandbox Code Playgroud)
换句话说,我不希望在例外中有一些不正确的元素来破坏我的主列表.这样简单吗?它FEELS我应该能够做到这里面一行的for循环(即没有明确检查x是masterlist的关键)
更新:对我来说,我的问题是询问列表和字典之间缺乏平行.例如:
l = []
l[0] = 2 #fails
l.append(2) #works
Run Code Online (Sandbox Code Playgroud)
使用子类化答案,您可以修改字典(可能是"safe_dict"或"explicit_dict"来执行类似的操作:
d = {}
d['a'] = '1' #would fail in my world
d.insert('a','1') #what my world is missing
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 15
你可以使用.update:
masterlist.update((x, False) for x in exceptions if masterlist.has_key(x))
Run Code Online (Sandbox Code Playgroud)
Dr *_*Kay 10
你可以继承一个dict类,覆盖它__setitem__来检查密钥是否存在(或者只对一个实例进行猴子修补).
样本类:
class a(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
dict.__setitem__(self, 'a', 'b')
def __setitem__(self, key, value):
if self.has_key(key):
dict.__setitem__(self, key, value)
a = a()
print a['a'] # prints 'b'
a['c'] = 'd'
# print a['c'] - would fail
a['a'] = 'e'
print a['a'] # prints 'e'
Run Code Online (Sandbox Code Playgroud)
您还可以使用某些函数来设置值,而无需检查是否存在更简单.
但是,我会更短......除非你在很多地方需要它,否则不要使用它.
| 归档时间: |
|
| 查看次数: |
59529 次 |
| 最近记录: |