Python Language Dictionary: Difference between revisions
Jump to navigation
Jump to search
Line 6: | Line 6: | ||
=Create a Dictionary= | =Create a Dictionary= | ||
A new dictionary instance is declared using the <code>{</code>< | A new dictionary instance is declared using the <code>{</code><code>}</code> syntax. The dictionary can be empty | ||
<syntaxhighlight lang='python'> | <syntaxhighlight lang='python'> | ||
d = {} | d = {} | ||
Line 12: | Line 12: | ||
or it can be populated with values: | or it can be populated with values: | ||
<syntaxhighlight lang='python'> | <syntaxhighlight lang='python'> | ||
d = {'a': 'b', 1: 2, | d = {'a': 'b', 1: 2, True: "this is true"} | ||
</syntaxhighlight> | </syntaxhighlight> | ||
It is good form to insert a space after <code>:</code>. | It is good form to insert a space after <code>:</code>. |
Revision as of 19:56, 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".
Create a Dictionary
A new dictionary instance is declared using the {
}
syntax. The dictionary can be empty
d = {}
or it can be populated with values:
d = {'a': 'b', 1: 2, True: "this is true"}
It is good form to insert a space after :
.
Access a Dictionary
Access Individual Elements
[]
, get()
An attempt to access an inexistent key ends up in a KeyError
exception being thrown.
Test the existence of a key.
Access:
d["key"]
Get All Keys
Get All Values
Modify a Dictionary
Modify Individual Elements
Add, modify, delete.