M03 - Dictionaries Flashcards
Dictionary definition + contents
- Object that stores a collection of data
- Has a key and a value or key-value pairs (think dictionary where there’s Word-Definition)
Key-Value Pairs example with 2 keys/how a dictionary prints out
{‘key1’ : value1 , ‘key2’ : value2 , etc.}
2 Important Rules for Dictionaries
- Keys must be immutable objects, like integers, floating-point decimals, or strings. Keys cannot be lists or any other time of mutable object
- Values in a dictionary can be objects of any type: integers, floating-point decimals, strings, Boolean values, datetime values, and lists
Initialize/Create an empty dictionary options
dict_variable = { }
dict_variable = dict( )
Standard format for creating a key in a dictionary and syntax example
-Place the key between single or double quotes and inside brackets [ ]
dict_variable[“key1”] = value1
Length of a dictionary
len(dict_variable)
items( ) method on dictionary and when it cannot be used
- Will return a list of tuples where the first element in each tuple is the key of the dictionary and the second element in each tuple is the value corresponding to that key
- Cannot use list indexing with the items( ) method
items( ) Syntax + output example
dict_variable.items( )
Output:
dict_variable( [ (‘key1’ , value1) , (‘key2’ , value2) , …] )
View Object - what it is and what it gives us
- Is the information inside the dict_variable( [ ] ) in the output
- Gives us a snapshot of what is in the dictionary (provides each key and respective value)
Get all Keys from Dictionary method and syntax
keys( )
dict_variable.keys( )
keys( ) method returns
Will return a view object that contains the keys of the dictionary as a list
dict_variable( [ ‘Key1’, ‘Key2’ , ‘Key3’ , …. ] )
Get all Values from Dictionary method and syntax
values( )
dict_varible.values( )
values( ) method returns
-Returns a view object that contains the values of the dictionary as a list
dict_variable( [‘value1’ , ‘value2’ , ‘value3’ …. ] )
2 ways to get a specific VALUE from a dictionary and a note about syntax
get( )
dict_variable[‘keyname’]
*both require the key to be in single or double quotes
get( ) syntax
dict_variable.get(‘keyname’)