我有一个字典是从我无权访问代码的函数传递给我的。在这本字典中有一个键叫做'time'
。 .我可以print d['time']
它打印出我期望的值。但是,当我遍历字典时,将跳过此键。还有 d.keys()
不包括它。如果重要,其他键是数字。
我该如何重新创建它?你如何在不知道名字的情况下看到隐藏的 key ?这可以撤消吗?
print type(d)
返回 <type 'dict'>
最佳答案
简单复现:
class fake_dict(dict):
def __getitem__(self, item):
if item == 'time':
return 'x'
d = fake_dict({'a': 'b', 'c': 'd'})
assert isinstance(d, dict)
assert 'time' not in d.keys()
print d # {'a': 'b', 'c': 'd'}
assert d['time'] == 'x'
关于python - 隐藏的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30674560/