A Crazy Python Dictionary Expression ?!

Real Python · Beginner ·🛠️ AI Tools & Apps ·9y ago

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 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

The video explains a surprising Python dictionary expression and provides a step-by-step breakdown of how Python processes it, covering key override issues due to Python's type hierarchy.

Key Takeaways
  1. Create a new dictionary with multiple keys
  2. Identify key override issues due to boolean subtype of integer
  3. Understand how Python processes dictionary expressions
💡 Python treats booleans as a subtype of integers, which can lead to key override issues in dictionary expressions.

Related AI Lessons

Up next
How to Open HPL Files (HP-GL Plotter)
File Extension Geeks
Watch →