A Crazy Python Dictionary Expression ?!
Key Takeaways
The video explains a surprising Python dictionary expression, where keys are overridden due to Python treating booleans as a subtype of integers, and provides a step-by-step breakdown of how Python processes the dictionary expression.
Full Transcript
hey and welcome to the next video in the python tricks Series so python tricks is a new book that I'm working on and it's kind of like an a buffet of awesome python features so um the goal with the book is to give you you know a really quick overview with a simple code example and kind of a guided walkr through one really cool aspect of python that you might not have heard about and this could be you know a little known syntactical feature a little known feature in the python standard library and it's it's all very practical stuff that's going to help you um get better in your python coding and so today um I want to cover a particular python trick that um I guess it's a little bit more quirky but uh it'll still lead to some really interesting considerations and uh so what I want to talk about today is a really crazy dictionary expression and so I'm going to move this out of the way here and uh yeah so this dictionary expression is uh pretty surprising at least it was really surprising to me when I saw it for the first time and so let me just type this out here real quick so basically what we're doing here is we're putting in creating a new dictionary and we're putting in a bunch of keys and um uh keep like keep those keys in mind and just kind of look at those keys and and maybe you'll know what's going to happen when I hit return and evaluate this expression so um I'm just going to wait for a second like think about this what what do you think this is going to what do you think is going to happen when we evaluate this expression what do you think the outcome of this would be like actually pause the video and think about this for like a minute or two and then come back to it okay ready I'm going to run this now boom okay so the result we're getting here is a dictionary which just one key it has just one key true and the value is maybe and actually when we look at the original expression here that's kind of surprising in my books right uh because well the true key well that that was the key we put here and actually the value was supposed to be yes and then that no and one doesn't show up at all and here we have uh one 1.0 the float value uh as the key and and this may be value for that key now actually shows up here so this this seems like a complete mess and uh this seems you know this is a really surprising result so I want to untangle that now because it's going to show you um I think it's going to help you to better understanding or deeper understanding of uh the python interpreter and how python python works like certainly helped me with that well the first thing we should do here is try to break down how python processes our dictionary expression here I think that gives us a hint right because it kind of makes us realize that well as we're assigning these Keys they're we're overriding them right like the key one the integer one overrides the key true and the integer um 1 Point uh the float 1.0 overrides the other key and well I mean it doesn't really override the key but it overrides the value right so we we end up with like it seems to be taking the keyy from the first time we set this particular key and it seems to take the value from the last time we set this particular key I mean at this point we don't really know like why are these considered all the same key but it kind of gives us a hunch right like what what could be wrong here like let's play python detective here so if we're actually try and like uh validate this assumption or test this assumption let's just compare all of the keys that we're using here and actually python tells us that true one and 1.0 they're all considered um equal they're all considered to be the same key and so that's the case because python actually treats booleans as a subtype of the inte integer type and you can dig that up in the python documentation here in the uh standard type hierarchy so um when we search for Bo here you can see here that the Boolean type is a subtype of the integer type and Boolean values behave like the values zero and one respectively in almost all contexts with the or the exception being that when converted to a string the strings false or true are returned respectively and that's our explanation right that pretty much explains what's going on here it doesn't really explain why we're not ending up with the key uh 1.0 at the end but it kind of explains how these keys are getting overridden so what we can see here that as we're building up this dictionary we're overriding the value for that key and because you might be wondering why we're still ending up with um true as the value or like the name for that key that is the case because if if the keys are considered equal python doesn't actually have to update the object right if they're considered equal it can just keep the initial object and update the value and so what you end up with if we play through this again let's play through this again let's actually let's uh let's start with a new uh with a new dictionary here so if we play through this again we're going to say okay Y is true equals yes and we print out y's okay that makes sense right and now we're going to say Y is 1 equals no all right what do we expect now well we expect the key to remain the same and it to be overridden with um with a new value and now if we uh set the key one to maybe then again we expect to end up with the result that we've gotten out of this dictionary expression very early on so this seems to confirm our our Theory here all right and that dispels most of this magic here now there might be you know at the back of your head you might be thinking oh aren't python dictionaries hash Maps or something is that like is that what a hash Collis is um sort of uh and actually I've got a lot more to say on this topic to kind of really dive down into the hashmap stuff and really uh untangle where that that comes into place so you can either check out the book for that um or you can read a blog post that I wrote about this earlier so uh that that there are going to be some pointers for you to dive more deeply into this and they're going to be linked in the description for the video and again if you enjoyed this video or this video series then please check out my book uh called python tricks and I hope I see you soon
Original Description
https://dbader.org/python-tricks ► Master advanced features in Python with free & easy to digest code examples
We're going to pry apart this slightly unintuitive Python dictionary expression to find out what’s going on in the uncharted depths of the Python interpreter.
A while ago I shared a Python one-liner as a “Python riddle” on Twitter and it got some interesting reactions:
{ True: 'yes', 1: 'no', 1.0: 'maybe' }
Take a quick moment to think about what this dict expression will evaluate to.
You might be surprised...
Watch the video or read the full article to learn more about Python dictionaries, hashing and key collisions: https://dbader.org/blog/python-mystery-dict-expression
FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery
SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube
* * *
► Python Developer MUGS, T-SHIRTS & MORE: https://nerdlettering.com
FREE Python Tutorials & News:
» Python Tutorials: https://dbader.org
» Python News on Twitter: https://twitter.com/@dbader_org
» Weekly Tips for Pythonistas: https://dbader.org/newsletter
» Subscribe to this channel: https://dbader.org/youtube
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 39 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
▶
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
Related AI Lessons
⚡
⚡
⚡
⚡
n8n Automation Repurpose Video Content: The 2025 Production Guide
Dev.to AI
You’re Still Paying $200/Month for AI Tools You Could Replace With a Free Local Setup Tonight
Medium · Data Science
Top 10 AI Tools Every College Student Should Know in 2026
Medium · AI
Answer Calculator: Step-by-Step Math Help
Medium · Machine Learning
🎓
Tutor Explanation
DeepCamp AI