Python Language Dictionary: Difference between revisions
Line 30: | Line 30: | ||
print(d['a']) | print(d['a']) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
An attempt to access an inexistent key will throw a <code>KeyError</code> exception. To avoid the exception, use <code>[[#get.28.29_Function|get()]]</code> instead. | An attempt to access an inexistent key will throw a <code>KeyError</code> exception. To avoid the exception, use <code>[[#get.28.29_Function|get()]]</code> instead, or [[#Test_the_Existence_of_a_Key|test the existence of the key]] first. | ||
===<tt>get()</tt> Function=== | ===<tt>get()</tt> Function=== |
Revision as of 20:15, 16 February 2022
Internal
Overview
A dictionary is a mutable collection of key-value pairs. The pairs can be accessed and modified. Each key is unique within the key set, and can be an instance of any immutable type: boolean, integer, float, tuple, string, etc. In other programming languages, the same data structure is referred to as "associative array" or "hash tables" or "hash maps".
Key Discussion
The keys 1
and True
are equivalent. Why?
Create a Dictionary
A new dictionary instance is declared using the {...}
syntax. The curly braces are placed around comma-separated key: value
pairs. The dictionary can be empty
d = {}
or it can be populated with values:
d = {'a': 'b', 1: 2}
It is good form to insert a space after :
. A comma is tolerated after the last pair.
Access a Dictionary
Access Individual Elements
Individual dictionary elements can be accessed with the []
syntax or with the get()
function.
Access with [] Syntax
The []
syntax can only be used with keys that exist in the dictionary:
d = {'a': 'b'}
print(d['a'])
An attempt to access an inexistent key will throw a KeyError
exception. To avoid the exception, use get()
instead, or test the existence of the key first.
get() Function
d = {'a': 'b'}
print(d.get('a')) # will display 'a'
print(d.get('no-such-key')) # will display None
Test the Existence of a Key
The existence of the key can be tested with in
:
if 'some-key' in d:
print("key exists")
get()
can also be used:
if d.get('some-key') is not None:
print("key exists")
Get All Keys
Get All Values
Modify a Dictionary
Modify Individual Elements
Add, modify, delete.