How to Use ChainMap
So, it’s from this
collections module, as I told you already, and we’re going to import this
collections, in general, is just a really useful library of awesome stuff, all to do with some kind of object collection, as you might gather from the name.
ChainMap is a dictionary-like class. It’s not in fact a variant of a dictionary, but it is dictionary-like. It allows you to chain together multiple dictionaries into one big iterating thing. Let’s take a look at how it works.
veggies. It takes in dictionaries. And then let’s take a look at it, what is it? Well, it’s a
ChainMap, and as you can see it has these dictionaries within it, and it prints them out when you try to print it.
But the cool thing is that you can iterate through it just like you can iterate through a dictionary. And you can print out
key and then
chained_map at that
key, and you can get all of these dictionary items all at once without having to worry about saying, you know,
for key in fruits:
for key in veggies: and then print out both of them in a row in multiple loops.
You can just do one big loop with this
ChainMap. So it’s pretty cool, and it has also—which is great—it has the same
.values() functions that the dictionary has natively. And so you can do all of these same different things with it, which is pretty sweet. So, as I said, it implements
.items(), and that’s really important.
So that’s a really important thing to note just for if you want to use this in real life. So,
ChainMap. Essentially, it’s like a big dictionary which combines other dictionaries into one giant iterable class.
Become a Member to join the conversation.