L8 Py DataStructures Dictionaries

1
Dictionaries Introduction A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. Mapping You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item. Creating a dictionary >>> dict1 = dict() >>> dict1 {} >>> dict1['one'] = 'uno' >>> dict1 {'one': 'uno'} >>> dict1['two'] = 'dos' >>> dict1['three'] = 'tres' >>> dict1 {'three': 'tres', 'two': 'dos', 'one': 'uno'} Common functions/operators >>> len(dict1) 3 >>> 'one' in dict1 # in operator True >>> 'four' in dict1 False

description

Basics of Python dictionaries.

Transcript of L8 Py DataStructures Dictionaries

Page 1: L8 Py DataStructures Dictionaries

Dictionaries

IntroductionA dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

MappingYou can think of a dictionary as a mapping between a set of indices (which are called keys) and a set ofvalues. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.

Creating a dictionary>>> dict1 = dict() >>> dict1 {} >>> dict1['one'] = 'uno' >>> dict1 {'one': 'uno'} >>> dict1['two'] = 'dos' >>> dict1['three'] = 'tres' >>> dict1 {'three': 'tres', 'two': 'dos', 'one': 'uno'}

Common functions/operators>>> len(dict1) 3>>> 'one' in dict1 # in operatorTrue >>> 'four' in dict1 False