今日已更新 428 条资讯 | 累计 22190 条内容
关于我们

The Complete Guide to Python Dictionary Behavior in Technical Interviews

Ameer Abdullah 2026年07月16日 20:31 3 次阅读 来源:Dev.to

Dictionary ordering, key hashing, view objects, and the iteration traps that catch experienced developers. Dictionaries are the most used Python data structure in production code and one of the most tested in technical interviews. Most developers use them comfortably but have gaps in their understanding of how they actually work. Insertion Order Is Guaranteed in Python 3.7 data = {} data [ " c " ] = 3 data [ " a " ] = 1 data [ " b " ] = 2 print ( list ( data . keys ())) print ( list ( data . values ())) Output: ['c', 'a', 'b'] ['3', '1', '2'] Since Python 3.7, dictionaries maintain insertion order as a language guarantee. Before that, order was an implementation detail. This is worth knowing because interview questions sometimes try to catch candidates who believe dictionaries are unordered. Mutating a Dictionary While Iterating data = { " a " : 1 , " b " : 2 , " c " : 3 } for key in data : if data [ key ] == 2 : del data [ key ] Output: RuntimeError: dictionary changed size during iteration You cannot add or remove keys from a dictionary while iterating over it. The safe pattern is to iterate over a copy of the keys: for key in list ( data . keys ()): if data [ key ] == 2 : del data [ key ] Or collect keys to delete first: to_delete = [ k for k , v in data . items () if v == 2 ] for key in to_delete : del data [ key ] Dictionary Views data = { " a " : 1 , " b " : 2 , " c " : 3 } keys = data . keys () values = data . values () items = data . items () print ( keys ) data [ " d " ] = 4 print ( keys ) Output: dict_keys(['a', 'b', 'c']) dict_keys(['a', 'b', 'c', 'd']) Dictionary views are live views of the dictionary. They update automatically when the dictionary changes. This surprises developers who expect .keys() to return a static snapshot. The get() Method Versus Direct Access data = { " a " : 1 , " b " : 2 } print ( data [ " a " ]) print ( data . get ( " a " )) print ( data . get ( " z " )) print ( data . get ( " z " , 0 )) try : print ( data [ " z " ]) except Key

本文内容来源于互联网,版权归原作者所有
查看原文