惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Spread Privacy
Spread Privacy
T
Threatpost
C
Cisco Blogs
P
Palo Alto Networks Blog
AI
AI
Cyberwarzone
Cyberwarzone
NISL@THU
NISL@THU
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Latest news
Latest news
AWS News Blog
AWS News Blog
D
Docker
S
SegmentFault 最新的问题
博客园 - 聂微东
WordPress大学
WordPress大学
Vercel News
Vercel News
S
Securelist
爱范儿
爱范儿
J
Java Code Geeks
Know Your Adversary
Know Your Adversary
S
Schneier on Security
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
D
DataBreaches.Net
宝玉的分享
宝玉的分享
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MongoDB | Blog
MongoDB | Blog
Engineering at Meta
Engineering at Meta
K
Kaspersky official blog
美团技术团队
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
量子位
博客园_首页
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
Google Online Security Blog
Google Online Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
腾讯CDC
T
Threat Research - Cisco Blogs
雷峰网
雷峰网
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python dict Internals: Hash Tables, Collision Resolution, and Hash Attacks
James Lee · 2026-05-17 · via DEV Community

Hash Values

Python's built-in hash() function returns an object's hash value. Hash tables rely on hash values to index elements:

object ──▶ hash(object) ──▶ hash value ──▶ slot index in hash table

Enter fullscreen mode Exit fullscreen mode

For a hash table to work correctly, key objects must satisfy two conditions:

  1. The hash value must not change during the object's lifetime.
  2. Objects that compare equal must have the same hash value.

Objects satisfying these conditions are called hashable. Only hashable objects can be used as keys in a hash table. This is why dict, set, and other hash-table-backed containers require hashable keys.

Among Python's built-in types, all immutable objects are hashable; mutable objects like list and dict are not:

>>> hash([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Enter fullscreen mode Exit fullscreen mode

Unhashable objects cannot be used as dict keys:

>>> {[]: 'list is not hashable'}
TypeError: unhashable type: 'list'

>>> {{}: 'dict is not hashable either'}
TypeError: unhashable type: 'dict'

Enter fullscreen mode Exit fullscreen mode

User-defined objects are hashable by default — their hash value is derived from their memory address, and any two distinct objects are considered unequal:

>>> class A:
...     pass
...
>>> a = A()
>>> b = A()
>>> hash(a), hash(b)
(-9223372036573452351, -9223372036573452365)
>>> a == b
False

Enter fullscreen mode Exit fullscreen mode

How Is the Hash Value Computed?

The answer is a hash function. As we know from the object model, object behavior is determined by the type object. Hash value computation is one such behavior — it's stored in the tp_hash function pointer of the type object. The built-in hash() function delegates to tp_hash to compute and return the value.

For str, the hash function is unicode_hash in Objects/unicodeobject.c:

PyTypeObject PyUnicode_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "str",                        /* tp_name */
    sizeof(PyUnicodeObject),      /* tp_size */
    // ...
    (hashfunc) unicode_hash,      /* tp_hash */
    // ...
};

Enter fullscreen mode Exit fullscreen mode

For user-defined objects, you can override the default hash behavior by implementing __hash__ and __eq__. For example, if a Tag instance is uniquely identified by its value field:

class Tag:

    def __init__(self, value, title):
        self.value = value
        self.title = title

    def __hash__(self):
        return hash(self.value)

    def __eq__(self, other):
        return self.value == other.value

Enter fullscreen mode Exit fullscreen mode

Since hash values are used frequently and never change during an object's lifetime, they are cached inside the object to avoid recomputation. For str, the internal hash field stores the cached value.

A good hash function must distribute hash values uniformly across the hash space. The more similar two values are, the more different their hash values should be.


Hash Collisions

Two different objects can have the same hash value. Also, the number of slots in a hash table is far smaller than the full hash value space. This means multiple keys can map to the same slot — a hash collision.

hash(key1) % table_size = 3  ┐
                              ├─▶ both map to slot 3 → collision!
hash(key3) % table_size = 3  ┘

Enter fullscreen mode Exit fullscreen mode

There are two common strategies to resolve hash collisions:

  • Separate chaining
  • Open addressing

Separate Chaining

Each slot maintains a linked list. All keys that hash to the same slot are stored in the corresponding list:

Hash Index        Linked Lists
┌───┐
│ 0 │──▶ NULL
├───┤
│ 1 │──▶ [key2] ──▶ NULL
├───┤
│ 2 │──▶ NULL
├───┤
│ 3 │──▶ [key1] ──▶ [key3] ──▶ NULL   ← both hash to slot 3
├───┤
│ 4 │──▶ NULL
└───┘

Enter fullscreen mode Exit fullscreen mode

Open Addressing (Python's Approach)

Python uses open addressing — data is stored directly in the hash slots. If a slot is occupied, try another one.

Insert key3 (hashes to slot 3, already occupied by key1):

┌───┬───────┐
│ 0 │       │
├───┼───────┤
│ 1 │       │
├───┼───────┤
│ 2 │       │
├───┼───────┤
│ 3 │ key1  │ ← slot 3 occupied
├───┼───────┤
│ 4 │       │
├───┼───────┤
│ 5 │ key3  │ ← probe finds slot 5, insert here ✅
└───┴───────┘

Enter fullscreen mode Exit fullscreen mode

The i-th probe tries slot (base + dᵢ) % size. The probing strategy depends on the function dᵢ.

Linear probingdᵢ = 2 * i:

Probe sequence: slot 3 → 5 → 7 → 9 → ...

Enter fullscreen mode Exit fullscreen mode

Quadratic probingdᵢ = i²:

Probe sequence: slot 3 → 4 → 7 → 12 → ...

Enter fullscreen mode Exit fullscreen mode

Both methods have a weakness: a fixed probe sequence increases collision probability when multiple keys share the same starting slot.

key, key2, key3 all hash to slot 1:
Fixed probe sequence: 1 → 3 → 7 → 13 → ...
All three follow the SAME path → high collision rate ❌

Enter fullscreen mode Exit fullscreen mode

Python's Perturbation-Based Probing

Python improves on this by incorporating the object's hash value into the probe sequence, making each key's probe path unique:

key  (hash=0b...0101): probe path → 1 → 6 → 3 → ...
key2 (hash=0b...1010): probe path → 1 → 4 → 9 → ...
key3 (hash=0b...1111): probe path → 1 → 8 → 2 → ...

Enter fullscreen mode Exit fullscreen mode

The implementation is in lookdict inside Objects/dictobject.c:

static Py_ssize_t _Py_HOT_FUNCTION
lookdict(PyDictObject *mp, PyObject *key,
         Py_hash_t hash, PyObject **value_addr)
{
    size_t i, mask, perturb;
    PyDictKeysObject *dk;
    PyDictKeyEntry *ep0;

top:
    dk = mp->ma_keys;
    ep0 = DK_ENTRIES(dk);
    mask = DK_MASK(dk);
    perturb = hash;
    i = (size_t)hash & mask;

    for (;;) {
        Py_ssize_t ix = dk_get_index(dk, i);
        // key comparison omitted

        // compute next slot
        // perturb incorporates the hash value → unique probe sequence per key
        perturb >>= PERTURB_SHIFT;
        i = (i*5 + perturb + 1) & mask;
    }
    Py_UNREACHABLE();
}

Enter fullscreen mode Exit fullscreen mode


Hash Attacks

Before Python 3.3, hash values were computed solely from the object itself — no randomness involved. This meant the same object always produced the same hash value across any two interpreter instances:

# Python 2, process 1 (pid=2878)
>>> hash('fasion')
3629822619130952182

# Python 2, process 2 (pid=2915)
>>> hash('fasion')
3629822619130952182   # identical ← vulnerability

Enter fullscreen mode Exit fullscreen mode

An attacker could craft a large number of keys that all hash to the same value, then POST them as JSON to a Python 2 web server. The server would build a dict from this data — and every single key would collide. Hash table performance degrades from O(1) to O(N), effectively taking the server down. This is a hash flooding attack.

The Fix: Hash Salting (Python 3.3+)

The solution is simple — add a salt:

  1. When the interpreter starts, generate a random number as the salt.
  2. The hash function incorporates both the object itself and the random salt.

Since the attacker cannot know the interpreter's internal random salt, they cannot pre-compute colliding keys.

# Python 3.7, process 1
>>> hash('fasion')
7411353060704220518

# Python 3.7, process 2
>>> hash('fasion')
1784735826115825426   # different every time ✅

Enter fullscreen mode Exit fullscreen mode

Python's hash algorithm is implemented in Python/pyhash.c.


The Delete Operation

Now let's look at how dict handles deletion. Consider this scenario:

State after inserting key1, key2, key3:

Hash Index    Entry Storage
┌───┬──────┐  ┌───┬──────┐
│ 0 │      │  │ 0 │ key1 │
├───┼──────┤  ├───┼──────┤
│ 1 │  1   │──▶ 1 │ key2 │
├───┼──────┤  ├───┼──────┤
│ 2 │      │  │ 2 │      │
├───┼──────┤  ├───┼──────┤
│ 3 │      │  │ 3 │      │
├───┼──────┤  └───┴──────┘
│ 4 │      │
├───┼──────┤
│ 5 │  0   │──▶ key1 (slot 5, entry 0)
├───┼──────┤
│ 6 │  2   │──▶ key3 (slot 6, entry 2) ← key3 collided at slot 1, moved to slot 6
└───┴──────┘

Enter fullscreen mode Exit fullscreen mode

If we delete key2 by simply marking slot 1 as EMPTY:

┌───┬──────┐
│ 1 │EMPTY │  ← slot 1 cleared
├───┼──────┤
│ 6 │  2   │  key3 hashes to slot 1, probes... finds EMPTY → thinks key3 doesn't exist ❌
└───┴──────┘

Enter fullscreen mode Exit fullscreen mode

This breaks the probe chain — key3 becomes unreachable!

The Fix: DUMMY Tombstone

Instead of marking the slot as EMPTY, Python marks it as DUMMY — a tombstone that signals "keep probing, don't stop here":

┌───┬──────┐
│ 1 │DUMMY │  ← tombstone, probe chain intact
├───┼──────┤
│ 6 │  2   │  key3 hashes to slot 1, sees DUMMY → continues probing → finds slot 6 ✅
└───┴──────┘

Enter fullscreen mode Exit fullscreen mode

Slot state constants are defined in Objects/dict-common.h:

#define DKIX_EMPTY (-1)
#define DKIX_DUMMY (-2)  /* Used internally */
#define DKIX_ERROR (-3)

Enter fullscreen mode Exit fullscreen mode

Reusing Deleted Entry Storage

Python doesn't bother reusing deleted entry storage slots. When a new key is inserted, it simply uses the next available entry:

Insert key4 after deleting key2:

Entry storage:
┌───┬──────┐
│ 0 │ key1 │
├───┼──────┤
│ 1 │ key2 │ ← deleted (wasted, ignored)
├───┼──────┤
│ 2 │ key3 │
├───┼──────┤
│ 3 │ key4 │ ← new entry goes here ✅
└───┴──────┘

Enter fullscreen mode Exit fullscreen mode

Yes, some storage slots may be wasted — but that's acceptable.

Resize and Rebuild

When entry storage is exhausted, Python performs a resize: allocates a brand-new hash table and migrates all live entries into it.

Before resize:                After resize:
┌───┬──────┐                 ┌───┬──────┐
│ 0 │ key1 │                 │ 0 │ key1 │
├───┼──────┤   ──rebuild──▶  ├───┼──────┤
│ 1 │ key2 │(deleted)        │ 1 │ key3 │  ← only live entries copied
├───┼──────┤                 ├───┼──────┤
│ 2 │ key3 │                 │ 2 │ key4 │
├───┼──────┤                 ├───┼──────┤
│ 3 │ key4 │                 │   │      │  ← fresh empty slots
└───┴──────┘                 └───┴──────┘

Enter fullscreen mode Exit fullscreen mode

The new table size is determined by the current number of live elements, so a resize can result in expansion, shrinkage, or no change in capacity. Either way, after the rebuild, fresh entry slots are available again.