PYTHON Dictionary
PYTHON Dictionary
Key Value
Name Age
Sam 20
Ram 21
Gauri 30
Maitree 34
John 29
So, with the help of dictionary we can represent the above table as:
2. Creating a Dictionary
2.1 Simple Dictionary
In Python, a Dictionary can be created by placing sequence of elements within
curly { } braces, separated by ‘comma’.
Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its Key:value.
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
#empty dictionary
My_dict = { }
#dictionary with integer keys
My_dict = { 1: 'apple', 2: 'ball'}
o Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are
two dictionary each having one key and value.
o It’s not compulsory to have both the values as dictionary in nested dictionary.
o We can also write as,
Dict = {1: 'Welcome', 2: 'To', 3:{'A' : 'Summer', 'B' : 'Training', 'C' : 'Program'}}
Representation:
KEYS VALUE
S
1 Welcome
2 To
3
NESTED KEYS
A Summer
B Training
C Program
my_dict['age'] = 27
print("Changed : ", my_dict)
my_dict['address'] = 'Downtown'
print("Added : ",my_dict)
'sex': 'Female'} }
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people)
Output:
The method, popitem() can be used to remove and return the arbitrary item (key, value) form the
dictionary. All the items can be removes at once using the clear() method.
We can also use the del keyword to remove the individual items or the entire dictionary itself.
Example: Output:
squares = {1:1, 2:4, 3:9, 4:16, 5:25} Original Dict : {1:1, 2:4, 3:9, 4:16, 5:25}
print("Original Dict : ", squares) Pop : {1: 1, 2: 4, 3: 9, 5: 25}
print(squares.pop(4)) Popitem : {2: 4, 3: 9, 5: 25}
print("Pop : ", squares) Delete : {2: 4, 3: 9}
print(squares.popitem()) Clear : {}
print("Popitem : ",squares) Delete 2 :
del squares[5]
print("Delete : ",squares)
squares.clear()
print("Clear : ",squares)
# Throws Error
# print(squares)
KeyError: 5
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
7. Copy A Dictionary
Example:
statesAndCapitals = { 'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna' }
print('List Of given states:\n')
# Iterating over keys
for key in statesAndCapitals:
print(key)
Output:
List Of given states:
Gujarat
Maharashtra
Rajasthan
Bihar
Output:
List Of given states and their capitals:
Gujarat : Gandhinagar
Maharashtra : Mumbai
Rajasthan : Jaipur
Bihar : Patna
Output:
Person ID: 1
Name: John
Age: 27
Sex: Male
b) Keys must be immutable, which means you can use strings, numbers or tuples as dictionary
keys but something like [‘key’] is not allowed.
Example:
dict1 = {["name"]: "Meena", "Age":5}
print(dict1["name"])
Output:
TypeError Traceback (most
recent call last)
<ipython-input-11-4b8af70cacc5> in <module>
----> 1 dict1 = {["name"]: "Meena", "Age":5}
2 print(dict1["name"])
METHODS DESCRIPTION
clear() The clear() method removes all items from the dictionary.
copy() They copy() method returns a shallow copy of the dictionary.
fromkeys() Create a new dictionary with keys from seq and values set to value.
get() It is a conventional method to access a value for a key.
items() Returns a list of dict’s (key, value) tuple pairs
keys() Returns list of dictionary dict’s keys
pop() Removes and returns an element from a dictionary having the
given key.
popitem() Removes the arbitrary key-value pair from the dictionary and
returns it as tuple.
setdefault() Set dict[key]=default if key is not already in dict
update() Adds dictionary dict2’s key-values pairs to dict
dictionary_name.values() returns a list of all the values available in a given dictionary.
Now that you are clear with the concepts of dictionary, you are ready to solve the Jupyter notebook
provided to you.
References:
1. https://www.programiz.com/python-programming/dictionary
2. https://www.tutorialspoint.com/python/python_dictionary.htm
3. https://www.w3schools.com/python/python_dictionaries.asp
4. https://www.geeksforgeeks.org/python-dictionary/
5. https://www.programiz.com/python-programming/nested-dictionary
6. https://www.geeksforgeeks.org/iterate-over-a-dictionary-in-python/