Dictionary
instance of dict class. un-ordered sequences of key:value paired elements. use curly braces {} to create a dict. key should be in single or double quotes. but single is preferred. value could hold any type of data. dictioneries are mutable object.
my_guitar = {
'brand': 'Ibanez',
'price': 1000,
'color': 'black'
}get element
use dict['key'] to get element from dict. you cannot use dot notation to get element from dict. because dot notation is used to access object attributes. and key in dict is not an attribute.
my_guitar_brand = my_guitar['brand']
print(my_guitar_brand)
# Ibanezyou can also use get('key') to access element from dict and it is recommended. if element is not found in dict, it will return None. you can set a default value to return if element is not found.
my_guitar_price = my_guitar.get('price', 0)
print(my_guitar_price)
# 1000 if element is found
# 0 if element is not foundchange element
use dict['key'] = value ato change element in dict.
my_guitar['brand'] = 'Fender'
print(my_guitar)
# {'brand': 'Fender', 'price': 1000, 'color': 'black'}adding element
use dict['key'] = value to add element in dict.
my_guitar['year'] = 2023
print(my_guitar)
# {'brand': 'Fender', 'price': 1000, 'color': 'black', 'year': 2023}delete element
use del dict['key'] to delete element from dict.
del my_guitar['year']
print(my_guitar)
# {'brand': 'Fender', 'price': 1000, 'color': 'black'}methods of dict
there are methods of dict.
keys()- returns asequenceof keys in dict. which is an instance ofdict_keysclass. we can convert the sequence to list usinglist().values()- returns a sequence of values in a dict.items()- returns a sequence ofkey:valuepairs in dict, which is an instance ofdict_itemsclass. we can convert the sequence to list usinglist().clear()- removes all elements from dict.copy()- returns a copy of dict.
nested dictionary
value of a key in dict can also be a dict. to access a nested dict, use dict['key']['nested_key'].
access non existence element
return KeyError if key does not exist. But if you use get method no error will be returned, instead returned None.