PYTHON NOTES JEGAN K K
DICTIONARY IN PYTHON:
Dictionary in python is used in many forms namely for creating adjacency list for nodes/vertices in a
graph implementation and for json data loading in python.
It is a combination of keys and values.
Syntax = py_dict = dict() # for creating empty dictionary
py-dict = {1: 'Apple', 2: 'Mango'}
In the above example 1 & 2 are the keys and 'Apple' & 'Mango' are the respective values.
KEYS() - To get the keys alone from a dict we use keys() function.
Syntax => py_dict.keys()
VALUES() - To get the key’s corresponding value from python dictionary we use values() function.
Syntax => py_dict.values()
In certain scenario, if we need to convert a list of lists to a dictionary, the list must contain key and
value pairs respectively. So if there are more than 2 values in the sublists, it becomes invalid to pack
values in a dictionary.
Syntax => a = [[1,'Apple'], [2,'Mango']] # list of lists
py_dict = dict(a) # converted dict from list of list
ADDING ITEMS TO DICT:
a = dict()
a['Item1'] = 'Box' # {'Item1' : 'Box'}
To add new value and their key to a dictionary, the key is to be present inside the '[]' brackets like
dict[key] = value.
DELETING FROM DICTIONARY:
Syntax => del a[key]
To delete a key and its pair value, the del keyword along with the dict_name followed by [key] is used
respectively.
DICTIONARY IN PYTHON:
Dictionary in python is used in many forms namely for creating adjacency list for nodes/vertices in a
graph implementation and for json data loading in python.
It is a combination of keys and values.
Syntax = py_dict = dict() # for creating empty dictionary
py-dict = {1: 'Apple', 2: 'Mango'}
In the above example 1 & 2 are the keys and 'Apple' & 'Mango' are the respective values.
KEYS() - To get the keys alone from a dict we use keys() function.
Syntax => py_dict.keys()
VALUES() - To get the key’s corresponding value from python dictionary we use values() function.
Syntax => py_dict.values()
In certain scenario, if we need to convert a list of lists to a dictionary, the list must contain key and
value pairs respectively. So if there are more than 2 values in the sublists, it becomes invalid to pack
values in a dictionary.
Syntax => a = [[1,'Apple'], [2,'Mango']] # list of lists
py_dict = dict(a) # converted dict from list of list
ADDING ITEMS TO DICT:
a = dict()
a['Item1'] = 'Box' # {'Item1' : 'Box'}
To add new value and their key to a dictionary, the key is to be present inside the '[]' brackets like
dict[key] = value.
DELETING FROM DICTIONARY:
Syntax => del a[key]
To delete a key and its pair value, the del keyword along with the dict_name followed by [key] is used
respectively.