Introduction to Dictionary

suggest change

A dictionary is an example of a key value store also known as Mapping in Python. It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key, they have very fast lookups. As they are primarily used for referencing items by key, they are not sorted.

creating a dict

Dictionaries can be initiated in many ways:

literal syntax

d = {}                        # empty dict
d = {'key': 'value'}          # dict with initial values
# Also unpacking one or multiple dictionaries with the literal syntax is possible

# makes a shallow copy of otherdict
d = {**otherdict}
# also updates the shallow copy with the contents of the yetanotherdict.
d = {**otherdict, **yetanotherdict}

dict comprehension

d = {k:v for k,v in [('key', 'value',)]}

see also: Comprehensions

built-in class: dict()

d = dict()                    # emtpy dict
d = dict(key='value')         # explicit keyword arguments
d = dict([('key', 'value')])  # passing in a list of key/value pairs
# make a shallow copy of another dict (only possible if keys are only strings!)
d = dict(**otherdict)

modifying a dict

To add items to a dictionary, simply create a new key with a value:

d['newkey'] = 42

It also possible to add list and dictionary as value:

d['new_list'] = [1, 2, 3]
d['new_dict'] = {'nested_dict': 1}

To delete an item, delete the key from the dictionary:

del d['newkey']

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Dictionary:
* Introduction to Dictionary

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
26 Dictionary
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve