Python Language Dictionary: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 25: Line 25:


===Access with <tt>[]</tt> Syntax===
===Access with <tt>[]</tt> Syntax===
The <code>[]</code> syntax can only be used with keys that exist in the dictionary:
<syntaxhighlight lang='py'>
d = {'a': 'b'}
print(d['a'])
</syntaxhighlight>


===<tt>get()</tt> Function===
===<tt>get()</tt> Function===

Revision as of 20:09, 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'])

get() Function

[], 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.

Modification with [] Syntax

Combine Dictionaries