ChainMap and MappingProxyType
00:23 This gives you the ability to provide search for a key across all of the dictionaries inside of the map. To demonstrate the use of the chain, I’m going to need a couple of dictionaries, so let me just quickly create them.
And now that I have the dictionaries, I’m going to import
ChainMap from the
collections library. To create a chain, I instantiate the
ChainMap, passing in the dictionaries that I wish to chain together.
Here’s the response for the key for the Beagle, and for the Atlas rocket, and finally for the Enterprise. Notice that there is an
"Enterprise" key in both the
chain responds back with the first key in the order of the dictionaries that it can find, so the response to the
"Enterprise" key is for the aircraft carrier rather than for the space shuttle.
Anything you do to the chain will impact the dictionaries that are associated with it. For example, let me delete the key
"Beagle". I’ve removed the key
"Beagle" from the
chain, and if you look at the
ships dictionary, it’s gone from there as well. In a similar fashion, let me add a new key to the
02:25 There’s your rocket. And unfortunately, this is where chains are a little problematic. Any additions to the chain get put into the first dictionary associated with the chain, so now I’ve got my Ariane rocket inside the wrong dictionary.
02:44 Generally, I would recommend just using the chains to manage reading keys from multiple dictionaries, and if you’re going to do insertions or deletions, it’s safer to do them directly to the dictionaries that were chained together, rather than to the chain itself.
And there it is.
'three' is inside of the proxy. As you’ve seen, there’s a variety of different types of dictionaries and maps inside of Python, besides just the built-in one. In the next lesson, I’ll talk about how to choose between them and give you some references for digging in further.
Become a Member to join the conversation.