4 ms·
TIL about dict reverse mapping in 3.10. This will be rather useful: people = { "Diane": 70, "Bob": 78, "Emma": 84 } keys =
by ssl232 4y ago
TIL about dict reverse mapping in 3.10. This will be rather useful:
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.
- matjet 4y agoI do not see the use for this, over the standard access methods. 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?
- ssl232 4y agoIt gives you access to the original dictionary from a view. I've not played with it yet but I guess that means you can modify it. 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:
- mjw1007 4y agoThe rationale was here. https://github.com/python/cpython/issues/85067#issuecomment-1093874030 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. »
- aidos 4y agoI don’t quite get the usecase for it. You’ve got the original dictionary that gives you exactly the same thing. There’s obviously something I’m not thinking of here but I’m not sure why I would want to trade the dictionary for a set of keys, that’s also the dictionary.
- dxdm 4y agoWhy would you want a collection of keys to behave like the mapping they came from? Why not pass around the dict itself, when you need access to the values? This seems like it extends the responsibilities of "keys" beyond what they should care about, and the mental overhead grows with it. Or is this about read-only access? There are better, more explicit ways to accomplish that.