Python dictionaries are mappings.
Mappings are collections of other objects and store objects by key.
Mappings map keys to associated values.
Dictionaries are mutable, they may be changed in place and can grow and shrink on demand.
When written as literals, dictionaries are coded in curly braces and consist of a series of "key: value" pairs.
As an example, consider the following three-item dictionary with keys "food," "quantity," and "color," perhaps the details of a hypothetical menu item?:
D = {'food': 'Test', 'quantity': 4, 'color': 'pink'} print( D )
We can index this dictionary by key to fetch and change the keys' associated values.
The dictionary index operation uses the same syntax as sequences.
D = {'food': 'Test', 'quantity': 4, 'color': 'pink'} print( D['food'] ) # Fetch value of key 'food' # from ww w . j ava 2 s . c om D['quantity'] += 1 # Add 1 to 'quantity' value print( D )
The following code starts with an empty dictionary and fills it out one key at a time.
D = {} D['name'] = 'Jack' # Create keys by assignment D['job'] = 'dev' D['age'] = 40 # w w w .j av a 2 s . co m print( D ) print( print(D['name']) )
Here, we're using dictionary keys as field names in a record that describes someone.