Juha-Matti Santala - Community Builder. Dreamer. Adventurer.
The home of a developer community specialist.
hamatti.orgThe home of a developer community specialist.
hamatti.orgpython from .models import Bread, BreadType # (here, Bread.bread_type is a ForeignKey to BreadType) breads_input = [{ 'id': 1, 'breadType': 'bun' } , ... ] for bread_data in breads: bread_type, type_created = BreadType.objects.get_or_create(type=bread_data['breadType']) bread, bread_created = Bread.objects.get_or_create(id=bread_data['id'], bread_type=bread_type) Here we process through some list of dictionaries (imagine itās read from a JSON file or queried from a REST API). First, we try to create a new BreadType but if one already exists, we return a reference to it rather than creating a new one every time. Then we create a bread, using the previous reference. If weād already have that specific bread inputted (maybe we ran the command twice), we want to get the existing one rather than creating new ones every time. I especially love using it in my data entry scripts / custom Django commands. Many of my applications operate on a model where I periodically input new data through these commands: for example in PokĆ©mon TCG app, when a new set is released. PokĆ©mon TCG is a great example. Right now, when my script reads in data for new cards, there are 13 such relationships between my Card model and other models. The codebase looks so much neater and easier to follow thanks to get_or_create. Edit later on Aug 8th: I rewrote the entire post to better explain what get_or_create does.python # dict constructor with keyword arguments scores = dict(Charlie=10, Patty=25, Snoopy=30) # dict constructor with tuples scores = dict(('Charlie', 10), ('Patty', 25), ('Snoopy', 30)) # key: value pairs scores = { 'Charlie': 10, 'Patty': 25, 'Snoopy': 30 } # dict comprehension data = [('Charlie', 10), ('Patty', 25), ('Snoopy', 30)] scores = { key: value for key, value in data } In each of these cases, the names are keys and numbers are values. Thereās one big restriction to the keys of dictionaries: they need to be hashable: > An object is hashable if it has a hash value which never changes during its > lifetime (it needs a __hash__() method), > and can be compared to other objects (it needs an __eq__() method). Hashable objects which > compare equal must have the same hash value. So you canāt use a list as a key for example because itās a mutable one. ### Accessing values Regardless of what was used to create it, we can access the values in a couple of ways: python scores = { 'Charlie': 10, 'Patty': 25, 'Snoopy': 30 } # With brackets scores['Charlie'] # == 10 # With .get() scores.get('Charlie') # == 10 The difference between these two is what happens when a key does not exist. python scores['Linus'] # raises KeyError: 'Linus' scores.get('Linus') # is None # We can give .get() a default value scores.get('Linus', 0) # == 0 ### Changing values Dictionaries are mutable data structures which means you can change their data. python # Set new value scores['Charlie'] = 15 # Modify a value scores['Charlie'] += 5 # Delete a key del scores['Charlie'] Since there is a direct āone key to one valueā relationship, dictionaries are very handy in collecting data for or counting values belonging to this key. Letās say we have a dataset where each time someone scores a point, their name is listed. We then want to count how may points each has: python marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] scores = {} # Creating an empty dict for person in marks: # Go through every mark if person not in scores: # If it's not in the dict yet, scores[person] = 0 # create an entry with starting value 0 scores[person] += 1 # Add 1 point to this person print(scores) # {'Charlie': 3, 'Patty': 1, 'Snoopy': 4} Weāll look a bit later how we can improve this with some of the special dictionaries but this basic structure of turning data into a dictionary is a fundamental basic to learn in Python. While the key needs to be hashable, the values can be anything. So instead of just increasing a number from zero upwards, we could store data as a list or another dictionary or whatever. ### Looping over python # By default, loops over keys in for-in for person in scores: print(person, scores[person]) # Loop over values for score in scores.values(): print(score) # Loop over both for person, score in scores.items(): print(person, score) ### Sorting a dictionary On a concept level, basic mapping does not have an order. In Python, dictionaries maintain the order the keys are inserted in and there are ways to force an order (like OrderedDict) but itās a good baseline to base your knowledge of dictionaries on. However, when looping over a dictionary, you often want the data to be in some sort of order. In the earlier example when we counted marks to a dictionary, we might want to print it in an order of most points to least. For this, we can use sorted function: python # Let's recreate our dictionary scores = {'Charlie': 3, 'Patty': 1, 'Snoopy': 4} for person in sorted(scores, key=scores.get, reverse=True): print(f'{person}: {scores[person]}') # Snoopy: 4 # Charlie: 3 # Patty: 1 The first argument to sorted is in this case our dictionary. The second key, key= is a single argument function that defines what is used for sorting (in this case, scores.get tells the function we want the values corresponding to the keys) and reverse= can be used to reverse the order from ascending to descending. Itās important to note that nothing internally in the dictionary changes when using sorted. It returns a new list with the keys sorted based on the sorting criteria. ### Youāll do just fine with dictionary for a long time Next, Iāll introduce some specialised dictionaries that are included in the standard library because developers have found these cases very useful. If youāre a new developer, I do recommend focusing on using and understanding the basic dictionary. Thereās nothing in the following dictionaries that you canāt do in the basic one. Brian Holt once said this in one of his containers course: > When I donāt know how my tools work, I tend to resent them because they add > complexity to my life. > > When I understand what they are doing for me > and what I no longer have to do because the tool is doing it for me, I tend to > really like my tools. Jumping into the more advanced use cases before understanding the basics really well can be detrimental. Finish this blog post to see whatās out there but donāt be afraid to manually write the code they would let you skip over and over again so that youāll gain a deeper understanding. ## defaultdict In the earlier example of creating and populating a dictionary, we had to check if a key existed before we could interact with it: python marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] scores = {} # Creating an empty dict for person in marks: # Go through every mark if person not in scores: # If it's not in the dict yet, scores[person] = 0 # create an entry with starting value 0 scores[person] += 1 # Add 1 point to this person print(scores) # {'Charlie': 3, 'Patty': 1, 'Snoopy': 4} Thereās a way to shortcut this by using a defaultdict: python from collections import defaultdict marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] # Create a new dictionary with # default value of 0 for each key scores = defaultdict(int) for person in marks: scores[person] += 1 print(scores) # defaultdict(<class 'int'>, {'Charlie': 3, 'Patty': 1, 'Snoopy': 4}) Passing int to defaultdict tells the dictionary to start from a default value of 0. You could also pass list and the default would be an empty list. As you can see comparing the two examples above, the code becomes way easier to read and comprehend. ## Counter Our example of counting things is such a common operation that thereās a special Counter dictionary for it. python from collections import Counter marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] scores = Counter(marks) print(scores) # Counter({'Snoopy': 4, 'Charlie': 3, 'Patty': 1}) Not only does Counter help us in creation of it but it has a couple of really handy methods. I have written about Counter before and rather than repeating myself here, I recommend reading through that post.