home
clear breadcrumbs
search
login
 
dictionary
import os os.system('clear') print('Dictionaries:') dict = {'name':'Robbie', 'age':44, 'courses':['math','comp-sci']} print(dict) # {'name':'Robbie', 'age':44, 'courses':['math','comp-sci']} print(dict['name']) # Robbie print(dict['courses']) # ['math','comp-sci'] print(dict.get('age')) # 44 # by using the method get when a key that not exist will return none or the second argument instead of exception # get(key, default value) print(dict.get('phone', 'Key not found')) # adding key / value dict['phone'] = '555-555-5555' # changing value dict['age'] = 45 print(dict) # {'name': 'Robbie', 'age': 45, 'courses': ['math', 'comp-sci'], 'phone': '555-555-5555'} # update method dict.update({'name':'Cathy','age':33, 'email':'cathy@gmail.com','courses':['math','poli-sci']}) print(dict) # deleting using del del dict['age'] print(dict) # {'name': 'Cathy', 'courses': ['math', 'poli-sci'], 'phone': '555-555-5555', 'email': 'cathy@gmail.com'} # getting the value from the key and deleting the key-value pair email = dict.pop('email') print(email) # cathy@gmail.com print(dict) # {'name': 'Cathy', 'courses': ['math', 'poli-sci'], 'phone': '555-555-5555'} print(len(dict)) # 3 print(dict.keys()) # dict_keys(['name', 'courses', 'phone']) print(dict.values()) # dict_values(['Cathy', ['math', 'poli-sci'], '555-555-5555']) print(dict.items()) # dict_items([('name', 'Cathy'), ('courses', ['math', 'poli-sci']), ('phone', '555-555-5555')]) for key, value in dict.items(): print(key, value) # name Cathy # courses ['math', 'poli-sci'] # phone 555-555-5555