A
dictionary is like an address-book where you can find the address or contact
details of a person by knowing only his/her name i.e. we associate keys (name)
with values (details). A dictionary is an associative array (also known as
hashes). Any key of the dictionary is associated (or mapped) to a value. The
values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs. Below example is a simple German-English dictionary:
Output:
· Python Dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair.
· Dictionaries are optimized to retrieve values when the key is known.
· Creating a dictionary is as simple as placing items inside curly braces { } separated by comma.
· An item has a key and the corresponding value expressed as a pair, key: value.
· While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.
Method |
Description |
Example |
clear() |
Remove all items form the dictionary. |
thisdict.clear() |
copy() |
Return a shallow copy of the dictionary. |
dict2 = thisdict.copy() |
fromkeys(seq[, v]) |
Return a new dictionary with keys from seq and value equal to v(defaults to None). |
thisdict = dict.fromkeys(x, y) |
get(key[,d]) |
Return the value of key. If key doesn’t exit, return d (defaults to None). |
x = car.get(“model") |
items() |
Return a new view of the dictionary’s items (key, value). |
x = thisdict.items() |
keys() |
Return a new view of the dictionary’s keys. |
x = thisdict.keys() |
pop(key[,d]) |
Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. |
thisdict.pop(“model") |
popitem() |
Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. |
thisdict.popitem() |
setdefault(key[,d]) |
If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). |
x = thisdict.setdefault(“model", “Brand") |
update([other]) |
Update the dictionary with the key/value pairs from other, overwriting existing keys. |
thisdict.update({“color": “White"}) |
values() |
Return a new view of the dictionary’s values |
x = thisdict.values() |
PROGRAMS TO PRACTICE
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print("1. Dictionary: ", my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print("2. Dictionary: ", my_dict)
# using dict()
### As you can see below, we can also create a dictionary using the built-in function dict().
my_dict = dict({1:'apple', 2:'ball'})
print("3. Dictionary: ", my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
print("4. Dictionary: ", my_dict)
marks = {}.fromkeys(['Math','English','Science'], 0)
for item in marks.items():
print(item)
#Return Value from copy()
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
new.clear()
print("New:" , new)
print("Original:", original)
#The method update() adds dictionary dict2's key-values pairs in to dict.
# This function does not return anything
dict = {1:'one', 2:'two'}
dict2 = {3:'three', 4:'four'}
dict.update(dict2)
print("dict is now: ",dict)
#Delete Keys from the Dictionary
dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
del dict['Charlie']
print("dict : ",dict)
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
for key in Dict.keys():
if key in Boys.keys():
print(True)
else:
print(False)
#Run below list example and see the output
#Did you expect the same output?
list1 = [3,4,5]
list2=list1
list3=list1.copy() #Shallow copy
list1.append(6)
print("List1 values: ",list1)
print("List2 values: ",list2)
print("List3 values: ",list3)
list1=[2,4,6]
Dictlist1={0:2,1:4,2:6}
tup1=(1,3,5)
print("Tuple: ",type(tup1))
print(tup1[1])
dict1={"key":"value",46:"Sachin tendulkar", 34:["Rahul Dravid",10000,231]} #{} for Dictionary
print(dict1["key"])
print(dict1[46])
print(dict1[34])
#FromKeys - will assign same values to multiple keys
dict2={}.fromkeys(["Science","Maths","Social"],0)
print(dict2)
#Iterate through the dictionary: items is combination of Key & Value
for item in dict2.items():
print(item)
#Sort dictionary based on keys
print(list(sorted(dict2.keys())))
#Update function of Dictionary
dict1.update(dict2)
print("Dict 1: ", dict1)
print("Dict 2: ", dict2)
#
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
for key in Dict.keys():
if key in Boys.keys():
print(True)
else:
print(False)
#======== Copy in Lists ================
list1 = [2,4,6,8]
list2=list1 # Deep Copy
list3=list1.copy() #Shallow Copy
list1.append(10)
list2.append(12)
print("List 1: ", list1) #2,4,6,8,10
print("List 2: ", list2) #2,4,6,8,10 |8
print("List 3: ", list3) #2,4,6,8,10 | 8
Assignments
1. # WAP to create a dictionary to use roll no. as
Key and Value to be a list with Student Name, class, favorite subject. Write
this using input and loops to create this dictionary and perform all the
functions discussed in the class