1. namedtuple
Often times when working with data, you will use a dictionary just so you can use key names to make reading the code and accessing the data easier to understand.
2. What is a namedtuple?
Python has another container called a namedtuple which is a tuple, but has names for each position of the tuple. This works well when you don't need the nested structure of a dictionary or desire each item to look identical, and don't want to add the overhead of a Pandas dataframe.
3. Creating a namedtuple
You create a namedtuple by passing a name for the tuple type and a list of field names. Let's begin by importing namedtuple from the collections module. Next we'll define our namedtuple. It's common practice to use Pascalcase (capitalizing each word) when naming namedtuples so I've used Eatery with a capital E for both the tuple name and the variable we stored the namedtuple as. Then we provide a list of fields we want on the nametuple. Now we can create our Eatery named tuples. I'm going to change our NYC Park eateries data into a list of namedtuples. I create an empty list then iterate over my nyc_eateries list creating an instance of my Eatery namedtuple by passing in the data from the loop as the arguments to my namedtuple.
4. Print the first element
Finally, let's print the first Eatery in the list. Now that we've got a list of named tuples let's see how we can use them.
5. Leveraging namedtuples
One of the great things about named tuples is that they can make code clearer because each field is available an as attribute. An attribute is basically a named field or data storage location. We can also depend on every instance of a namedtuple to have all the fields, although some might be empty or None in Python terms. This means we can always have safe access to a field without the need for a get method like a dictionary. Here I'm going to use the list of tuples we created in the prior slide, and print the name, park_id, and location for the first three entries in the list.
6. Let's practice!
Now it's your turn to practice.