D is for dictionaries - Python A to Z Dark _ □ ✕
  • Posts
  • About
  • Debug
Post

D is for dictionaries - Python A to Z

Published
2026-08-05 00:00 UTC (precision: second)
Source feed
Juha-Matti Santala - Community Builder. Dreamer. Adventurer. excluded
Link
https://hamatti.org/posts/d-is-for-dictionaries-python-a-to-z/
Canonical
https://hamatti.org/posts/d-is-for-dictionaries-python-a-to-z
Length
7423 runes
Extracted text
Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month. Dictionary is a data structure in Python that in other contexts and languages is called an associative array, akey-value store or a map. It’s a handy and efficient data structure for when you need to store and retrieve a value based on a key. This is a 101 level introduction to dictionaries. Dictionary Creating a dictionary The basic form of dictionary can be created in couple of ways: # 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: 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. 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. # 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: 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 # 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: # 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: 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: 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. 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.
Stored topics

Every stored assignment is listed, including rows below the current cutoff (0.75), so a missing tag can be explained.

Concept Code Score Meter Margin Origin Path
science and technology science-and-technology 0.99 4.46 direct science and technology
technology and engineering technology-and-engineering 0.98 3.76 ↑derived from 20000763 science and technology > technology and engineering
information technology and computer science information-technology-and-computer 0.98 3.76 direct science and technology > technology and engineering > information technology and computer science
economy, business and finance economy-business-and-finance 0.97 3.34 ↑derived from local:software-development economy, business and finance
products and services products-and-services 0.97 3.34 ↑derived from local:software-development economy, business and finance > products and services
computing and information technology computing-and-information-technology 0.97 3.34 ↑derived from local:software-development economy, business and finance > products and services > computing and information technology
software and applications software-and-applications 0.97 3.34 ↑derived from local:software-development economy, business and finance > products and services > computing and information technology > software and applications
Software development software-development 0.97 3.34 direct economy, business and finance > products and services > computing and information technology > software and applications > Software development
education education 0.75 1.08 direct education
Open source open-source 0.68 0.74 direct economy, business and finance > products and services > computing and information technology > software and applications > Open source
media and entertainment industry media-and-entertainment-industry 0.53 0.11 ↑derived from 20000306 economy, business and finance > products and services > media and entertainment industry
books and publishing books-and-publishing 0.53 0.11 direct economy, business and finance > products and services > media and entertainment industry > books and publishing
Cryptography cryptography 0.34 -0.65 direct science and technology > technology and engineering > information technology and computer science > Cryptography
artificial intelligence artificial-intelligence 0.32 -0.75 direct science and technology > technology and engineering > information technology and computer science > artificial intelligence
arts, culture, entertainment and media arts-culture-entertainment-and-media 0.27 -0.99 ↑derived from local:blogging arts, culture, entertainment and media
mass media mass-media 0.27 -0.99 ↑derived from local:blogging arts, culture, entertainment and media > mass media
social media social-media 0.27 -0.99 ↑derived from local:blogging arts, culture, entertainment and media > mass media > social media
Blogging blogging 0.27 -0.99 direct arts, culture, entertainment and media > mass media > social media > Blogging
Information security information-security 0.25 -1.11 direct science and technology > technology and engineering > information technology and computer science > Information security
arts and entertainment arts-and-entertainment 0.24 -1.16 ↑derived from 20000013 arts, culture, entertainment and media > arts and entertainment
literature literature 0.24 -1.16 direct arts, culture, entertainment and media > arts and entertainment > literature
environment environment 0.11 -2.09 direct environment
lifestyle and leisure lifestyle-and-leisure 0.10 -2.17 ↑derived from 20000538 lifestyle and leisure
leisure leisure 0.10 -2.17 direct lifestyle and leisure > leisure
society society 0.07 -2.55 direct society
natural science natural-science 0.06 -2.74 direct science and technology > natural science
game game 0.06 -2.74 ↑derived from local:mmorpg lifestyle and leisure > leisure > game
video game video-game 0.06 -2.74 ↑derived from local:mmorpg lifestyle and leisure > leisure > game > video game
MMORPG mmorpg 0.06 -2.74 direct lifestyle and leisure > leisure > game > video game > MMORPG
social sciences social-sciences 0.06 -2.84 direct science and technology > social sciences
film industry film-industry 0.05 -2.97 direct economy, business and finance > products and services > media and entertainment industry > film industry
hobby hobby 0.05 -2.98 direct lifestyle and leisure > leisure > hobby
health health 0.04 -3.20 ↑derived from 20000458 health
disease and condition disease-and-condition 0.04 -3.20 ↑derived from 20000458 health > disease and condition
mental health and disorder mental-health-and-disorder 0.04 -3.20 direct health > disease and condition > mental health and disorder
health treatment and procedure health-treatment-and-procedure 0.04 -3.25 ↑derived from 20000465 health > health treatment and procedure
diet diet 0.04 -3.25 direct health > health treatment and procedure > diet
crime, law and justice crime-law-and-justice 0.04 -3.28 ↑derived from 20000086 crime, law and justice
crime crime 0.04 -3.28 ↑derived from 20000086 crime, law and justice > crime
cyber crime cyber-crime 0.04 -3.28 direct crime, law and justice > crime > cyber crime
Tabletop gaming tabletop-gaming 0.04 -3.30 direct lifestyle and leisure > leisure > game > Tabletop gaming
sport sport 0.03 -3.39 direct sport
scientific research scientific-research 0.03 -3.40 ↑derived from 20000739 science and technology > scientific research
scientific exploration scientific-exploration 0.03 -3.40 ↑derived from 20000739 science and technology > scientific research > scientific exploration
space exploration space-exploration 0.03 -3.40 direct science and technology > scientific research > scientific exploration > space exploration
history history 0.03 -3.55 direct science and technology > social sciences > history
exercise and fitness exercise-and-fitness 0.03 -3.57 direct lifestyle and leisure > wellness > exercise and fitness
wellness wellness 0.03 -3.57 ↑derived from 20001239 lifestyle and leisure > wellness
fundamental rights fundamental-rights 0.03 -3.59 ↑derived from 20001300 society > fundamental rights
privacy privacy 0.03 -3.59 direct society > fundamental rights > privacy
competition discipline competition-discipline 0.03 -3.63 ↑derived from 20001183 sport > competition discipline
eSports esports 0.03 -3.63 direct sport > competition discipline > eSports
politics and government politics-and-government 0.03 -3.64 direct politics and government
family family 0.03 -3.64 direct society > family
climate change climate-change 0.02 -3.69 direct environment > climate change
culture culture 0.02 -3.74 direct arts, culture, entertainment and media > culture
podcast podcast 0.02 -3.82 direct economy, business and finance > products and services > media and entertainment industry > podcast
biology biology 0.02 -3.83 direct science and technology > natural science > biology
disaster, accident and emergency incident disaster-accident-and-emergency-incident 0.02 -3.88 direct disaster, accident and emergency incident
television television 0.02 -3.94 direct arts, culture, entertainment and media > mass media > television
animation animation 0.02 -4.04 direct arts, culture, entertainment and media > arts and entertainment > animation
weather weather 0.02 -4.08 ↑derived from 20001128 weather
weather forecast weather-forecast 0.02 -4.08 direct weather > weather forecast
Self-hosting self-hosting 0.02 -4.09 direct economy, business and finance > products and services > computing and information technology > Self-hosting
labour labour 0.01 -4.24 direct labour
human interest human-interest 0.01 -4.36 ↑derived from 20000498 human interest
award and prize award-and-prize 0.01 -4.36 direct human interest > award and prize
religion religion 0.01 -4.37 direct religion
conflict, war and peace conflict-war-and-peace 0.01 -4.42 direct conflict, war and peace
card game card-game 0.01 -4.53 direct lifestyle and leisure > leisure > game > card game
music music 0.01 -4.68 direct arts, culture, entertainment and media > arts and entertainment > music
board game board-game 0.01 -4.74 direct lifestyle and leisure > leisure > game > board game
public health public-health 0.01 -5.07 direct health > public health
food and drink enthusiasm food-and-drink-enthusiasm 0.01 -5.13 direct lifestyle and leisure > leisure > hobby > food and drink enthusiasm
lifestyle lifestyle 0.01 -5.18 ↑derived from 20001257 lifestyle and leisure > lifestyle
house and home house-and-home 0.01 -5.18 ↑derived from 20001257 lifestyle and leisure > lifestyle > house and home
gardening gardening 0.01 -5.18 direct lifestyle and leisure > lifestyle > house and home > gardening
consumer goods consumer-goods 0.00 -5.39 ↑derived from 20001160 economy, business and finance > products and services > consumer goods
handicrafts handicrafts 0.00 -5.39 direct economy, business and finance > products and services > consumer goods > handicrafts
streaming service streaming-service 0.00 -5.62 direct economy, business and finance > products and services > media and entertainment industry > streaming service
travel and tourism travel-and-tourism 0.00 -5.85 direct lifestyle and leisure > leisure > travel and tourism
visual arts visual-arts 0.00 -5.88 ↑derived from 20000036 arts, culture, entertainment and media > arts and entertainment > visual arts
photography photography 0.00 -5.88 direct arts, culture, entertainment and media > arts and entertainment > visual arts > photography

← Back to posts

feedtagger 0.1.0-dev model: modernbert-base-zeroshot-v2.0/int8@all-s256 651 posts 0 unclassified min score 0.75