by ssl232 · 4y ago · 0 comments
people = {
"Diane": 70,
"Bob": 78,
"Emma": 84
}
keys = people.keys()
# dict_keys(['Diane', 'Bob', 'Emma'])
keys.mapping["Bob"]
# 78
EDIT: I actually misunderstood this; see comments. The keys.mapping field does not point to the original dictionary. I guess this is actually just about consistency with the way other mappings work? Not so useful (to me) after all.Or is this about read-only access? There are better, more explicit ways to accomplish that.
people = {
"Diane": 70,
"Bob": 78,
"Emma": 84
}
people.get("Bob")
# 78
The common usecase is: for key in people.keys():
people.get(key)
vs keys = people.keys()
# dict_keys(['Diane', 'Bob', 'Emma'])
for key in keys:
keys.mapping[key]
What is the advantage?EDIT: apparently not:
>>> keys.mapping
mappingproxy({'Diane': 70, 'Bob': 78, 'Emma': 84})
In this case I actually don't know what the use case is :shrug:https://github.com/python/cpython/issues/85067#issuecomment-...
It seems a bit vague: « Exposing this attribute would help with introspection, making it possible to write efficient functions that operate on dict views. »