finished section on dictionaries in "native datatypes"

This commit is contained in:
Mark Pilgrim
2009-02-07 14:46:24 -05:00
parent 6e3e5cd2d7
commit baca4a8694
5 changed files with 120 additions and 240 deletions
+1 -1
View File
@@ -1 +1 @@
function getPreContent(e){if(e.nodeType==3){return e.nodeValue.replace(/</g,"&lt;").replace(/>/g,"&gt;")}if(e.nodeType!=1){return""}if(e.nodeName.toLowerCase()=="span"){return""}if(e.className&&e.className=="widgets"){return""}var d=e.childNodes;var c=d.length;var b="";for(var a=0;a<c;a++){b+=getPreContent(d[a])}return b}function plainTextOnClick(c){var b=document.getElementById(c);if(!b){return}var a=window.open("about:blank","plaintext","toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=400,left=35,top=75");a.document.open();a.document.write("<pre>"+getPreContent(b));a.document.close()}function toggleBlock(d){var c=document.getElementById(d);if(!c){return}var b=document.getElementById(d+"toggle");if(!b){return}var a=document.getElementById(d+"block");if(!a){return}if(b.firstChild.nodeValue=="show"){a.style.display="block";b.firstChild.nodeValue="hide"}else{a.style.display="none";b.firstChild.nodeValue="show"}}window.onload=function(){var b=document.getElementsByTagName("pre");for(var h=b.length-1;h>=0;h--){var k=b[h];if(k.className=="screen"||k.firstChild.nodeName.toLowerCase()=="code"){var a=k.id;if(!a){a="autopre"+h;k.id=a}k.innerHTML='<div id="'+a+'widgets" class="widgets">[<a id="'+a+'toggle" class="toggle" href="javascript:toggleBlock(\''+a+'\')">hide</a>] [<a id="'+a+'plaintext" href="javascript:plainTextOnClick(\''+a+'\')">open in new window</a>]</div><div id="'+a+'block">'+k.innerHTML+"</div>"}}for(var h=b.length-1;h>=0;h--){var k=b[h];var d=k.getElementsByTagName("span");if(d.length==0){continue}var p=k.nextSibling;while(p&&(p.nodeType!=1)){p=p.nextSibling}if(p.nodeName.toLowerCase()!="ol"){continue}var q=p.getElementsByTagName("li");if(q.length!=d.length){alert("Number of callouts != number of callout list items:\n"+k.innerHTML);continue}for(var g=d.length-1;g>=0;g--){var m=d[g].parentNode;var f=q[g];m._li=f;f._div=m;m.onmouseover=function(){this.className="hover";this._li.className="hover"};f.onmouseover=function(){this.className="hover";this._div.className="hover"};m.onmouseout=function(){this.className="";this._li.className=""};f.onmouseout=function(){this.className="";this._div.className=""}}}var e=document.getElementsByTagName("table");for(var h=e.length-1;h>=0;h--){var o=e[h];var n=document.getElementById("skip"+o.id);if(!n){continue}var r=n.getElementsByTagName("li");var c=o.getElementsByTagName("tr");if(r.length==0){continue}for(var g=c.length-1;g>=1;g--){var s=c[g];var l=r[g-1];s._li=l;l._tr=s;s.onmouseover=function(){this.className="hover";this._li.className="hover"};l.onmouseover=function(){this.className="hover";this._tr.className="hover"};s.onmouseout=function(){this.className="";this._li.className=""};l.onmouseout=function(){this.className="";this._tr.className=""}}}};
function getPreContent(e){if(e.nodeType==3){return e.nodeValue.replace(/</g,"&lt;").replace(/>/g,"&gt;")}if(e.nodeType!=1){return""}if(e.nodeName.toLowerCase()=="span"){return""}if(e.className&&e.className=="widgets"){return""}var d=e.childNodes;var c=d.length;var b="";for(var a=0;a<c;a++){b+=getPreContent(d[a])}return b}function plainTextOnClick(c){var b=document.getElementById(c);if(!b){return}var a=window.open("about:blank","plaintext","toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=400,left=35,top=75");a.document.open();a.document.write("<pre>"+getPreContent(b));a.document.close()}function toggleBlock(d){var c=document.getElementById(d);if(!c){return}var b=document.getElementById(d+"toggle");if(!b){return}var a=document.getElementById(d+"block");if(!a){return}if(b.firstChild.nodeValue=="show"){a.style.display="block";b.firstChild.nodeValue="hide"}else{a.style.display="none";b.firstChild.nodeValue="show"}}window.onload=function(){var p=document.getElementsByTagName("pre");for(var q=p.length-1;q>=0;q--){var c=p[q];if(c.className=="screen"||c.firstChild.nodeName.toLowerCase()=="code"){var n=c.id;if(!n){n="autopre"+q;c.id=n}var h="";var f=c.previousSibling;while(f&&(f.nodeType!=1)){f=f.previousSibling}if(f&&(f.nodeName.toLowerCase()=="p")&&(f.className=="download")){h=" "+f.innerHTML;f.parentNode.removeChild(f)}c.innerHTML='<div id="'+n+'widgets" class="widgets">[<a id="'+n+'toggle" class="toggle" href="javascript:toggleBlock(\''+n+'\')">hide</a>] [<a id="'+n+'plaintext" href="javascript:plainTextOnClick(\''+n+"')\">open in new window</a>]"+h+'</div><div id="'+n+'block">'+c.innerHTML+"</div>"}}for(var q=p.length-1;q>=0;q--){var c=p[q];var b=c.getElementsByTagName("span");if(b.length==0){continue}var e=c.nextSibling;while(e&&(e.nodeType!=1)){e=e.nextSibling}if(e.nodeName.toLowerCase()!="ol"){continue}var s=e.getElementsByTagName("li");if(s.length!=b.length){alert("Number of callouts != number of callout list items:\n"+c.innerHTML);continue}for(var o=b.length-1;o>=0;o--){var d=b[o].parentNode;var t=s[o];d._li=t;t._div=d;d.onmouseover=function(){this.className="hover";this._li.className="hover"};t.onmouseover=function(){this.className="hover";this._div.className="hover"};d.onmouseout=function(){this.className="";this._li.className=""};t.onmouseout=function(){this.className="";this._div.className=""}}}var k=document.getElementsByTagName("table");for(var q=k.length-1;q>=0;q--){var u=k[q];var r=document.getElementById("skip"+u.id);if(!r){continue}var l=r.getElementsByTagName("li");var m=u.getElementsByTagName("tr");if(l.length==0){continue}for(var o=m.length-1;o>=1;o--){var a=m[o];var g=l[o-1];a._li=g;g._tr=a;a.onmouseover=function(){this.className="hover";this._li.className="hover"};g.onmouseover=function(){this.className="hover";this._tr.className="hover"};a.onmouseout=function(){this.className="";this._li.className=""};g.onmouseout=function(){this.className="";this._tr.className=""}}}};
+1
View File
@@ -18,6 +18,7 @@ ul{list-style:none}
<ul>
<li><a href="table-of-contents.html">Table of contents</a> (<strong>not finalized</strong>)
<li><a href="your-first-python-program.html">Chapter 1. Your first Python program</a>
<li><a href="native-datatypes.html">Chapter 2. Native datatypes</a>
<li><a href="case-study-porting-chardet-to-python-3.html">Chapter 20. Case study: porting <code>chardet</code> to Python 3</a>
<li><a href="porting-code-to-python-3-with-2to3.html">Appendix A. Porting code to Python 3 with <code>2to3</code></a>
</ul>
+96 -202
View File
@@ -13,7 +13,7 @@ body{counter-reset:h1 2}
</head>
<body>
<p class="skip"><a href="#divingin">skip to main content</a>
<form action="http://www.google.com/cse" id="search"><div><input type="hidden" name="cx" value="014021643941856155761:l5eihuescdw"><input type="hidden" name="ie" value="UTF-8">&nbsp;<input name="q" size="31">&nbsp;<input type="submit" name="sa" value="Search"></div></form>
<form action="http://www.google.com/cse" id="search"><div><input type="hidden" name="cx" value="014021643941856155761:l5eihuescdw"><input type="hidden" name="ie" value="UTF-8">&nbsp;<input name="q" size="31">&nbsp;<input type="submit" name="root" value="Search"></div></form>
<p class="nav">You are here: <a href="/">Home</a> <span>&#8227;</span> <a href="table-of-contents.html">Dive Into Python 3</a> <span>&#8227;</span>
<h1>Native datatypes</h1>
<blockquote class="q">
@@ -23,6 +23,7 @@ body{counter-reset:h1 2}
<li><a href="#divingin">Diving in</a>
<li><a href="#booleans">Booleans</a>
<li><a href="#numbers">Numbers</a>
<!--
<ol>
<li><a href="#integers">Integers</a>
<li><a href="#floats">Floating point numbers</a>
@@ -31,13 +32,32 @@ body{counter-reset:h1 2}
<li><a href="#numberoperations">Common operations on numbers</a>
<li><a href="#math">The <code>math</code> module</a>
</ol>
-->
<li><a href="#lists">Lists</a>
<!--
<ol>
<li>Creating new a list
<li>Modifying a list
<li>Searching a list
<li>Deleting elements from a list
<li>Common operations on lists
</ol>
-->
<li><a href="#sets">Sets</a>
<!--
<ol>
<li>Creating a new set
<li>Modifying a set
<li>Deleting elements from a set
<li>Common operations on sets (union, intersection, and difference)
<li>Frozen sets
</ol>
-->
<li><a href="#dictionaries">Dictionaries
<li><a href="#none"><code>None</code></a>
</ol>
<h2 id="divingin">Diving in</h2>
<p class="fancy">A short digression is in order. Put aside <a href="your-first-python-program.html">your first Python program</a> for just a minute, and let's talk about Python's native datatypes. These types are the foundation on which you will build all your future Python programs.
<p class="fancy">A short digression is in order. Put aside <a href="your-first-python-program.html">your first Python program</a> for just a minute, and let's talk about datatypes. <a href="your-first-python-program.html#datatypes">Every variable has a datatype</a>, even though you don't declare it explicitly. Based on each variable's original assignment, Python figures out what type it is and keeps tracks of that internally.
<p>Python has many native datatypes. Here are the important ones:
<ol>
<li><b>Booleans</b> are either <code>True</code> or <code>False</code>.
@@ -67,19 +87,80 @@ body{counter-reset:h1 2}
<samp class="prompt">>>> </samp><kbd>size &lt; 0</kbd>
<samp>True</samp></pre>
<h2 id="numbers">Numbers</h2>
<h3 id="integers">Integers</h3>
<h3 id="floats">Floating point numbers</h3>
<h3 id="fractions">Fractions</h3>
<h3 id="complexnumbers">Complex numbers</h3>
<h3 id="numberoperations">Common operations on numbers</h3>
<h3 id="math">The <code>math</code> module</h3>
<p>FIXME
<h2 id="lists">Lists</h2>
<p>FIXME
<h2 id="sets">Sets</h2>
<p>FIXME
<h2 id="dictionaries">Dictionaries</h2>
<p>One of Python's most important datatypes is the dictionary, which defines one-to-one relationships between keys and values.
<blockquote class="note compare-perl5">
<p><span>&#x261E;</span>A dictionary in Python is like a hash in Perl 5. In Perl 5, variables that store hashes always start with a <code>%</code> character. In Python, variables can be named anything, and Python keeps track of the datatype internally.
</blockquote>
<p>Creating a dictionary is easy. The syntax is similar to <a href="#sets">sets</a>, but instead of values, you have key-value pairs. Once you have a dictionary, you can look up values by their key.
<pre class="screen">
<a><samp class="prompt">>>> </samp><kbd>a_dict = {"server":"db.diveintopython3.org", "database":"mysql"}</kbd> <span>&#x2460;</span></a>
<samp class="prompt">>>> </samp><kbd>a_dict</kbd>
<samp>{'server': 'db.diveintopython3.org', 'database': 'mysql'}</samp>
<a><samp class="prompt">>>> </samp><kbd>a_dict["server"]</kbd> <span>&#x2461;</span></a>
'db.diveintopython3.org'
<a><samp class="prompt">>>> </samp><kbd>a_dict["database"]</kbd> <span>&#x2462;</span></a>
'mysql'
<a><samp class="prompt">>>> </samp><kbd>a_dict["db.diveintopython3.org"]</kbd> <span>&#x2463;</span></a>
<samp class="traceback">Traceback (most recent call last):
File "&lt;stdin>", line 1, in &lt;module>
KeyError: 'db.diveintopython3.org'</samp></pre>
<ol>
<li>First, you create a new dictionary with two elements and assign it to the variable <var>a_dict</var>. Each element is a key-value pair, and the whole set of elements is enclosed in curly braces.
<li><code>'server'</code> is a key, and its associated value, referenced by <code>a_dict["server"]</code>, is <code>'db.diveintopython3.org'</code>.
<li><code>'database'</code> is a key, and its associated value, referenced by <code>a_dict["database"]</code>, is <code>'mysql'</code>.
<li>You can get values by key, but you can't get keys by value. So <code>a_dict["server"]</code> is <code>'db.diveintopython3.org'</code>, but <code>a_dict["db.diveintopython3.org"]</code> raises an exception, because <code>'db.diveintopython3.org'</code> is not a key.
</ol>
<p>Dictionaries do not have any predefined size limit. You can add new key-value pairs to a dictionary at any time, or you can modify the value of an existing key. Continuing from the previous example:
<pre class="screen">
<samp class="prompt">>>> </samp><kbd>a_dict</kbd>
<samp>{'server': 'db.diveintopython3.org', 'database': 'mysql'}</samp>
<a><samp class="prompt">>>> </samp><kbd>a_dict["database"] = "blog"</kbd> <span>&#x2460;</span></a>
<samp class="prompt">>>> </samp><kbd>a_dict</kbd>
<samp>{'server': 'db.diveintopython3.org', 'database': 'blog'}</samp>
<a><samp class="prompt">>>> </samp><kbd>a_dict["user"] = "mark"</kbd> <span>&#x2461;</span></a>
<a><samp class="prompt">>>> </samp><kbd>a_dict</kbd> <span>&#x2462;</span></a>
<samp>{'server': 'db.diveintopython3.org', 'user': 'mark', 'database': 'blog'}</samp>
<a><samp class="prompt">>>> </samp><kbd>a_dict["user"] = "dora"</kbd> <span>&#x2463;</span></a>
samp class="prompt">>>> </samp><kbd>a_dict</kbd>
<samp>{'server': 'db.diveintopython3.org', 'user': 'dora', 'database': 'blog'}</samp>
<a><samp class="prompt">>>> </samp><kbd>a_dict["User"] = "mark"</kbd> <span>&#x2464;</span></a>
<samp class="prompt">>>> </samp><kbd>a_dict</kbd>
<samp>{'User': 'mark', 'server': 'db.diveintopython3.org', 'user': 'dora', 'database': 'blog'}</samp></pre>
<ol>
<li>You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
<li>You can add new key-value pairs at any time. This syntax is identical to modifying existing values.
<li>The new dictionary item (key <code>'user'</code>, value <code>'mark'</code>) appears to be in the middle. In fact, it was just a coincidence that the elements appeared to be in order in the first example; it is just as much a coincidence that they appear to be out of order now.
<li>Assigning a value to an existing dictionary key simply replaces the old value with the new one.
<li>Will this change the value of the <code>user</code> key back to "mark"? No! Look at the key closely &mdash; that's a capital <kbd>U</kbd> in <kbd>"User"</kbd>. Dictionary keys are case-sensitive, so this statement is creating a new key-value pair, not overwriting an existing one. It may look similar to you, but as far as Python is concerned, it's completely different.
</ol>
<p>Dictionaries aren't just for strings. Dictionary values can be any datatype, including integers, booleans, arbitrary objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed. Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
<p>In fact, you've already seen a dictionary with non-string keys and values, in <a href="your-first-python-program.html#divingin">your first Python program</a>.
<pre><code>SUFFIXES = {1000: ('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'),
1024: ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')}</code></pre>
<p>Let's tear that apart in the interactive shell.
<pre class="screen">
<samp class="prompt">>>> </samp><kbd>SUFFIXES = {1000: ('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'),</kbd>
<samp class="prompt">... </samp><kbd> 1024: ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')}</kbd>
<a><samp class="prompt">>>> </samp><kbd>len(SUFFIXES)</kbd> <span>&#x2460;</span></a>
<samp>2</samp>
<a><samp class="prompt">>>> </samp><kbd>SUFFIXES[1000]</kbd> <span>&#x2461;</span></a>
<samp>('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')</samp>
<a><samp class="prompt">>>> </samp><kbd>SUFFIXES[1024]</kbd> <span>&#x2462;</span></a>
<samp>('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')</samp>
<a><samp class="prompt">>>> </samp><kbd>SUFFIXES[1000][3]</kbd> <span>&#x2463;</span></a>
<samp>'TB'</samp></pre>
<ol>
<li>As with <a href="#lists">lists</a> and <a href="#sets">sets</a>, the <code>len()</code> function gives you the number of items in a dictionary.
<li><code>1000</code> is a key in the <code>SUFFIXES</code> dictionary; its value is a tuple of eight items (eight strings, to be precise).
<li>Similarly, <code>1024</code> is a key in the <code>SUFFIXES</code> dictionary; its value is also a tuple of eight items.
<li>Since <code>SUFFIXES[1000]</code> is a tuple, you can address individual items in the tuple by their 0-based index.
</ol>
<h2 id="none"><code>None</code></h2>
<p><code>None</code> is a special constant in Python. It is a null value. <code>None</code> is not <code>False</code>; it is not <code>0</code>; it is not an empty string. Comparing <code>None</code> to anything other than <code>None</code> will always return <code>False</code>.
<p><code>None</code> is the only null value. It has its own datatype (<code>NoneType</code>). You can assign <code>None</code> to any variable, but you can not create other <code>NoneType</code> objects. All variables whose value is <code>None</code> are equal to each other.
@@ -101,193 +182,6 @@ body{counter-reset:h1 2}
<samp class="prompt">>>> </samp><kbd>x == y</kbd>
<samp>True</samp>
</pre>
<!--
<h2 id="odbchelper.dict">3.1. Introducing Dictionaries</h2>
<p>One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.<table id="compare.dict.perl" class="note" border="0" summary="">
<tr>
<td rowspan="2" align="center" valign="top" width="1%"><img src="images/note.png" alt="Note" title="" width="24" height="24"></td>
</tr>
<tr>
<td colspan="2" align="left" valign="top" width="99%">A dictionary in Python is like a hash in Perl. In Perl, variables that store hashes always start with a <code>%</code> character. In Python, variables can be named anything, and Python keeps track of the datatype internally.
</td>
</tr>
</table><table id="compare.dict.java" class="note" border="0" summary="">
<tr>
<td rowspan="2" align="center" valign="top" width="1%"><img src="images/note.png" alt="Note" title="" width="24" height="24"></td>
</tr>
<tr>
<td colspan="2" align="left" valign="top" width="99%">A dictionary in Python is like an instance of the <code>Hashtable</code> class in Java.
</td>
</tr>
</table><table id="compare.dict.vb" class="note" border="0" summary="">
<tr>
<td rowspan="2" align="center" valign="top" width="1%"><img src="images/note.png" alt="Note" title="" width="24" height="24"></td>
</tr>
<tr>
<td colspan="2" align="left" valign="top" width="99%">A dictionary in Python is like an instance of the <code>Scripting.Dictionary</code> object in Visual Basic.
</td>
</tr>
</table>
<h3>3.1.1. Defining Dictionaries</h3>
<div class="example"><h3 id="odbchelper.dict.define">Example 3.1. Defining a Dictionary</h3><pre class="screen"><samp class="prompt">>>> </samp>d = {"server":"mpilgrim", "database":"master"} <img id="odbchelper.dict.1.1" src="images/callouts/1.png" alt="1" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'database': 'master'}
<samp class="prompt">>>> </samp>d["server"]<img id="odbchelper.dict.1.2" src="images/callouts/2.png" alt="2" border="0" width="12" height="12">
'mpilgrim'
<samp class="prompt">>>> </samp>d["database"] <img id="odbchelper.dict.1.3" src="images/callouts/3.png" alt="3" border="0" width="12" height="12">
'master'
<samp class="prompt">>>> </samp>d["mpilgrim"] <img id="odbchelper.dict.1.4" src="images/callouts/4.png" alt="4" border="0" width="12" height="12">
<samp class="traceback">Traceback (innermost last):
File "&lt;interactive input>", line 1, in ?
KeyError: mpilgrim</span></pre><div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.1.1"><img src="images/callouts/1.png" alt="1" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">First, you create a new dictionary with two elements and assign it to the variable <var>d</var>. Each element is a key-value pair, and the whole set of elements is enclosed in curly braces.
</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.1.2"><img src="images/callouts/2.png" alt="2" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left"><code>'server'</code> is a key, and its associated value, referenced by <code>d["server"]</code>, is <code>'mpilgrim'</code>.
</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.1.3"><img src="images/callouts/3.png" alt="3" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left"><code>'database'</code> is a key, and its associated value, referenced by <code>d["database"]</code>, is <code>'master'</code>.
</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.1.4"><img src="images/callouts/4.png" alt="4" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">You can get values by key, but you can't get keys by value. So <code>d["server"]</code> is <code>'mpilgrim'</code>, but <code>d["mpilgrim"]</code> raises an exception, because <code>'mpilgrim'</code> is not a key.
</td>
</tr>
</table>
<h3>3.1.2. Modifying Dictionaries</h3>
<div class="example"><h3 id="odbchelper.dict.modify">Example 3.2. Modifying a Dictionary</h3><pre class="screen"><samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'database': 'master'}
<samp class="prompt">>>> </samp>d["database"] = "pubs" <img id="odbchelper.dict.2.1" src="images/callouts/1.png" alt="1" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'database': 'pubs'}
<samp class="prompt">>>> </samp>d["uid"] = "sa" <img id="odbchelper.dict.2.2" src="images/callouts/2.png" alt="2" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}</pre><div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.2.1"><img src="images/callouts/1.png" alt="1" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.2.2"><img src="images/callouts/2.png" alt="2" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">You can add new key-value pairs at any time. This syntax is identical to modifying existing values. (Yes, this will annoy
you someday when you think you are adding new values but are actually just modifying the same value over and over because
your key isn't changing the way you think it is.)
</td>
</tr>
</table>
<p>Note that the new element (key <code>'uid'</code>, value <code>'sa'</code>) appears to be in the middle. In fact, it was just a coincidence that the elements appeared to be in order in the first
example; it is just as much a coincidence that they appear to be out of order now.<table id="tip.dictorder" class="note" border="0" summary="">
<tr>
<td rowspan="2" align="center" valign="top" width="1%"><img src="images/note.png" alt="Note" title="" width="24" height="24"></td>
</tr>
<tr>
<td colspan="2" align="left" valign="top" width="99%">Dictionaries have no concept of order among elements. It is incorrect to say that the elements are &#8220;out of order&#8221;; they are simply unordered. This is an important distinction that will annoy you when you want to access the elements of
a dictionary in a specific, repeatable order (like alphabetical order by key). There are ways of doing this, but they're
not built into the dictionary.
</td>
</tr>
</table>
<p>When working with dictionaries, you need to be aware that dictionary keys are case-sensitive.
<div class="example"><h3 id="odbchelper.dict.case">Example 3.3. Dictionary Keys Are Case-Sensitive</h3><pre class="screen">
<samp class="prompt">>>> </samp>d = {}
<samp class="prompt">>>> </samp>d["key"] = "value"
<samp class="prompt">>>> </samp>d["key"] = "other value" <img id="odbchelper.dict.5.1" src="images/callouts/1.png" alt="1" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'key': 'other value'}
<samp class="prompt">>>> </samp>d["Key"] = "third value" <img id="odbchelper.dict.5.2" src="images/callouts/2.png" alt="2" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'Key': 'third value', 'key': 'other value'}
</pre><div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.5.1"><img src="images/callouts/1.png" alt="1" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">Assigning a value to an existing dictionary key simply replaces the old value with a new one.</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.5.2"><img src="images/callouts/2.png" alt="2" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">This is not assigning a value to an existing dictionary key, because strings in Python are case-sensitive, so <code>'key'</code> is not the same as <code>'Key'</code>. This creates a new key/value pair in the dictionary; it may look similar to you, but as far as Python is concerned, it's completely different.
</td>
</tr>
</table>
<div class="example"><h3 id="odbchelper.dictionarytypes">Example 3.4. Mixing Datatypes in a Dictionary</h3><pre class="screen"><samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}
<samp class="prompt">>>> </samp>d["retrycount"] = 3 <img id="odbchelper.dict.3.1" src="images/callouts/1.png" alt="1" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}
<samp class="prompt">>>> </samp>d[42] = "douglas" <img id="odbchelper.dict.3.2" src="images/callouts/2.png" alt="2" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
<samp class="computeroutput">{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master',
42: 'douglas', 'retrycount': 3}</span></pre><div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.3.1"><img src="images/callouts/1.png" alt="1" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even
other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match
as needed.
</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.3.2"><img src="images/callouts/2.png" alt="2" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left">Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match
key datatypes within a dictionary.
</td>
</tr>
</table>
<h3>3.1.3. Deleting Items From Dictionaries</h3>
<div class="example"><h3 id="odbchelper.dict.del">Example 3.5. Deleting Items from a Dictionary</h3><pre class="screen"><samp class="prompt">>>> </samp>d
<samp class="computeroutput">{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master',
42: 'douglas', 'retrycount': 3}</samp>
<samp class="prompt">>>> </samp>del d[42] <img id="odbchelper.dict.4.1" src="images/callouts/1.png" alt="1" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}
<samp class="prompt">>>> </samp>d.clear() <img id="odbchelper.dict.4.2" src="images/callouts/2.png" alt="2" border="0" width="12" height="12">
<samp class="prompt">>>> </samp>d
{}</pre><div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.4.1"><img src="images/callouts/1.png" alt="1" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left"><code>del</code> lets you delete individual items from a dictionary by key.
</td>
</tr>
<tr>
<td width="12" valign="top" align="left"><a href="#odbchelper.dict.4.2"><img src="images/callouts/2.png" alt="2" border="0" width="12" height="12"></a>
</td>
<td valign="top" align="left"><code>clear</code> deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary without any items.
</td>
</tr>
</table>
<div class="itemizedlist">
<h3>Further Reading on Dictionaries</h3>
<ul>
<li><a href="http://www.ibiblio.org/obp/thinkCSpy/" title="Python book for computer science majors"><i class="citetitle">How to Think Like a Computer Scientist</i></a> teaches about dictionaries and shows how to <a href="http://www.ibiblio.org/obp/thinkCSpy/chap10.htm">use dictionaries to model sparse matrices</a>.
<li><a href="http://www.faqts.com/knowledge-base/index.phtml/fid/199/">Python Knowledge Base</a> has a lot of <a href="http://www.faqts.com/knowledge-base/index.phtml/fid/541">example code using dictionaries</a>.
<li><a href="http://www.activestate.com/ASPN/Python/Cookbook/" title="growing archive of annotated code samples">Python Cookbook</a> discusses <a href="http://www.activestate.com/ASPN/Python/Cookbook/Recipe/52306">how to sort the values of a dictionary by key</a>.
<li><a href="http://www.python.org/doc/current/lib/"><i class="citetitle">Python Library Reference</i></a> summarizes <a href="http://www.python.org/doc/current/lib/typesmapping.html">all the dictionary methods</a>.
</ul>
-->
<p class="c">&copy; 2001-4, 2009 <span>&#x2133;</span>ark Pilgrim, <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">CC-BY-3.0</a>
</body>
</html>
+17 -35
View File
@@ -47,41 +47,23 @@ ul li ol{margin:0;padding:0 0 0 2.5em}
</ol>
<li><a href="native-datatypes.html">Native Python datatypes</a>
<ol>
<li><a href="native-datatypes.html#divingin">Diving in</a>
<li><a href="native-datatypes.html#booleans">Booleans</a>
<li>Numbers
<ol>
<li>Integers
<li>Floating point numbers
<li>Fractions
<li>Complex numbers
<li>Common operations on numbers
<li>The <code>math</code> module
</ol>
<li>Lists
<ol>
<li>Creating new a list
<li>Modifying a list
<li>Searching a list
<li>Deleting elements from a list
<li>Common operations on lists
</ol>
<li>Sets
<ol>
<li>Creating a new set
<li>Modifying a set
<li>Deleting elements from a set
<li>Common operations on sets <!-- union, intersection, and difference -->
<li>Frozen sets
</ol>
<li>Dictionaries
<ol>
<li>Creating a new dictionary
<li>Modifying a dictionary
<li>Deleting items from a dictionary
<li>Common operations on dictionaries
</ol>
<li><a href="native-datatypes.html#none"><code>None</code></a>
<li><a href="native-datatypes.html#divingin">Diving in</a>
<li><a href="native-datatypes.html#booleans">Booleans</a>
<li><a href="native-datatypes.html#numbers">Numbers</a>
<!--
<ol>
<li><a href="native-datatypes.html#integers">Integers</a>
<li><a href="native-datatypes.html#floats">Floating point numbers</a>
<li><a href="native-datatypes.html#fractions">Fractions</a>
<li><a href="native-datatypes.html#complexnumbers">Complex numbers</a>
<li><a href="native-datatypes.html#numberoperations">Common operations on numbers</a>
<li><a href="native-datatypes.html#math">The <code>math</code> module</a>
</ol>
-->
<li><a href="native-datatypes.html#lists">Lists</a>
<li><a href="native-datatypes.html#sets">Sets</a>
<li><a href="native-datatypes.html#dictionaries">Dictionaries
<li><a href="native-datatypes.html#none"><code>None</code></a>
</ol>
<li>Strings
<ol>
+5 -2
View File
@@ -22,6 +22,9 @@ body{counter-reset:h1 1}
<ol>
<li><a href="#divingin">Diving in</a>
<li><a href="#declaringfunctions">Declaring functions</a>
<ol>
<li><a href="#datatypes">How Python's datatypes compare to other programming languages</a>
</ol>
<li><a href="#readability">Writing readable code</a>
<ol>
<li><a href="#docstrings">Docstrings</a>
@@ -80,7 +83,7 @@ if __name__ == "__main__":
<h2 id="declaringfunctions">Declaring functions</h2>
<p>Python has functions like most other languages, but it does not have separate header files like <abbr>C++</abbr> or <code>interface</code>/<code>implementation</code> sections like Pascal. When you need a function, just declare it, like this:
<pre><code>def approximate_size(size, a_kilobyte_is_1024_bytes=True):</code></pre>
<p>Note that the keyword <code>def</code> starts the function declaration, followed by the function name, followed by the arguments in parentheses. Multiple arguments are separated with commas.
<p>The keyword <code>def</code> starts the function declaration, followed by the function name, followed by the arguments in parentheses. Multiple arguments are separated with commas.
<p>Also note that the function doesn't define a return datatype. Python functions do not specify the datatype of their return value; they don't even specify whether or not they return a value. (In fact, every Python function returns a value; if the function ever executes a <code>return</code> statement, it will return that value, otherwise it will return <code>None</code>, the Python null value.)
<blockquote class="note">
<p><span>&#x261E;</span>In some languages, functions (that return a value) start with <code>function</code>, and subroutines (that do not return a value) start with <code>sub</code>. There are no subroutines in Python. Everything is a function, all functions return a value (even if it's <code>None</code>), and all functions start with <code>def</code>.
@@ -89,7 +92,7 @@ if __name__ == "__main__":
<blockquote class="note compare-java compare-cplusplus">
<p><span>&#x261E;</span>In Java, <abbr>C++</abbr>, and other statically-typed languages, you must specify the datatype of the function return value and each function argument. In Python, you never explicitly specify the datatype of anything. Based on what value you assign, Python keeps track of the datatype internally.
</blockquote>
<h3>How Python's Datatypes Compare to Other Programming Languages</h3>
<h3 id="datatypes">How Python's datatypes compare to other programming languages</h3>
<p>An erudite reader sent me this explanation of how Python compares to other programming languages:
<dl>
<dt>statically typed language</dt>