Dictionaries
Reference:
Many programming languages provide an "associative array" datatype which represents an object with named attributes. Associative arrays are said to have "key/value" pairs, where the "key" represents the name of the attribute and the "value" represents the attribute's value.
Python's implementation of the associative array concept is known as a "dictionary". A Python dictionary comprises curly braces ({}) containing one or more key/value pairs, with each key separated from its value by a colon (:) and each key/value pair separated by a comma (,).
Example dictionaries:
{}
{"a": 1, "b": 2, "c": 3}
{"a": 1, "b": 2, "c": 3, "fruits": ["apple", "banana", "pear"]} # dictionaries can contain lists, or even other nested dictionaries
{"first_name": "Ophelia", "last_name": "Clark", "message": "Hello Again"}Each dictionary is similar to a row in a CSV-formatted spreadsheet or a record in a database, where the dictionary's "keys" represent the column names and its "values" represent the cell values.
city
name
league
New York
Yankees
major
New York
Mets
major
Boston
Red Sox
major
New Haven
Ravens
minor
Operations
Access individual object attributes by their key:
Add or update or remove attributes from an object:
Its possible to separate the dictionaries keys from its values, and also to iterate through each pair:
Last updated
Was this helpful?