Pythonically using dictionaries
1. Pythonically using dictionaries
So far, we've been working with dictionaries in a straight forward manner, but Python has more efficient ways to work with them. We refer to these manners of interacting as being Pythonic.2. Working with dictionaries more pythonically
Previously, we looped through dictionary keys then used the keys to get the values we desired. Python provides an items() method which returns a dict_items object, but we can iterate over it as a list of key/value tuples. If I use the dot items() method on my original art_galleries dictionary it returns a tuple of the gallery name and the phone number. I can use tuple unpacking to go ahead and expand that into its two components in the loop. Finally, I print them so you can see the information. Now let's look at a more Pythonic method for checking if data is present in a dictionary.3. Checking dictionaries for data
Earlier, we used the get method to safely look for keys, and we can use that to check to see if a key is in a dictionary. However, Python provides the in operator to see if a key is in a dictionary. It returns a boolean (True or False). Here I'm checking to see if 11234 is in the art_galleries dictionary, and since I deleted that key earlier it returns false. Since it returns a boolean, it is often used in conditionals statements like an if/else statement. Here if the key 10010 is in the art_galleries dictionary I'm going to print a message saying that it was found and with the value of the key.4. Let's practice!
Okay, time to see if we can check for data in dictionaries and use them in a pythonic manner.Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.