- read

Learning Python -Datatypes(IV)

Technomadlyf 11

Sequence Datatype consists of an ordered collection of elements that can be accessed by using number indices. Here, we are going to discuss the unordered collection of elements. They are not accessed using these index numbers.

Dictionary

It is a mutable unordered collection of elements. It is stored in pairs containing key : value pairs. Unlike sequences, dictionaries are indexed using the keys. The keys in the dictionary should be unique i.e, there should not be any duplicates.

Keys are created using {}

#here name, Username, age are keys
# Techno , Technomad, ? are values
dct = {"name": "Techno", "Username": "Technomad", "age":"?"}
print(dct)

Output:

{'name': 'Techno', 'Username': 'Technomad', 'age': '?'}

Instead of number indices, we can use keys to access the values in the dictionaries

print(dct['Username'])

Output:

Technomad

You can also use .get('key') to get the values the advantage is that it will not return an error if the key is not available in the dictionary

print(dct['Userage']) # Returns error

Output:

--------------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-4-32f2a16035ff> in <module>()
----> 1 print(dct['Userage'])
KeyError: 'Userage'

example using .get()

print(dct.get('Username'))print(dct.get('Userage')) # will return None by default you can #change it if you wantprint(dct.get('Userage', '23')) # will return 23 if the key is not #in the dictionary

Output:

Technomad 
None
23

Dictionaries are mutable, i.e; the values in the dictionary can be changed

dct["name"] = "Raj" # changing values in a dictionary
print(dct)
dct["Userage"] = 22 # Adding new element to the dictionary
print(dct)

Output:

{'name': 'Raj', 'Username': 'Technomad', 'age': '?'}
{'name': 'Raj', 'Username': 'Technomad', 'age': '?', 'Userage': 22}

Length Of Dictionary

The number of key-valuein the dictionary can be easily found by using the function len()

print(len(dct)) # number key - value pairs in dictionary

Output:

4

Deleting the Elements in a Dictionary

You can elements in a dictionary using the following functions

del can be used to delete elements in a dictionary

del dct['Userage'] #deletes the particular element in the #dictionary
print(dct)

Output:

{'name': 'Raj', 'Username': 'Technomad', 'age': '?'}

.pop()deletes and return the desired value

dct.pop('age') # delets and returns the delered value

Output:

?

.popitem() deletes a random element in the dictionary

dct.popitem() # deletes an randomitem
print(dct)

Output:

{'name': 'Raj', 'Username': 'Technomad'}

You can use the clear function to clear the elements in the dictionary

dct.clear() #clears the entire dictionary
print(dct)

Output:

{}

You can also delete the existence of dictionary from memory using the function del

del dct # deletes the dictionary from the memoryprint(dct)

Output

-------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-23-8aa615dbeea1> in <module>()
1 del dct # deletes the dictionary from the memory
----> 2 print(dct)
NameError: name 'dct' is not defined

Some Built-In Functions in Dictionary

.values() .items() .keys() can be used to get the list of keys and values in the dictionary.

dct = {"name": "Techno", "Username": "Technomad", "age":"?"}
print(dct.items()) #returns key-value as list of tuples
print(dct.keys()) # returns list of keysprint(dct.values()) # returns the list of values

Output:

dict_items([('name', 'Techno'), ('Username', 'Technomad'), ('age', '?')])dict_keys(['name', 'Username', 'age'])dict_values(['Techno', 'Technomad', '?'])

The values returned by these functions can be used to loop through the elements in the dictionary

for i in dct.keys():
print(i +':'+dct[i]) # prints key and values

Output:

name:Techno 
Username:Technomad
age:?

Sets

Sets are unordered collections of items. Sets are mutable and do not contain any duplicates. Since sets are unordered you cannot access elements using their indices.

Sets are created using {}.

st = {}
print(st)
st = {"apple", "banana", "mango", "apple"}
print(st) #here you can see the repeated apple is not stored in #memory

Output:

{} 
{'banana', 'mango', 'apple'}

You can get the length of the set using len()

print(len(st))

Output:

3

Adding Elements to a Set

You can add elements to a set using .add() function. You can also add elements from other Iterables to set using .update() function

st.add('orange')
print(st)
st.update(['jackfruit','guava'])
print(st)

Output:

{'banana', 'mango', 'apple', 'orange'} 
{'mango', 'orange', 'guava', 'jackfruit', 'banana', 'apple'}

Removing Elements from a Set

You can delete elements in a set using the following methods

.discard() - removes value from the set, does not raise an error if the value is not in the set.

.remove() - removes value from the set, raises an error if the value is not present.

.pop() - removes a random element

.clear() - removes all the elements from the set

st.discard("mango")
print(st)
st.remove('guava')
print(st)
st.pop()
print(st)
st.clear()
print(st)

Output:

{'orange', 'guava', 'jackfruit', 'banana', 'apple'} 
{'orange', 'jackfruit', 'banana', 'apple'}
{'jackfruit', 'banana', 'apple'}
set()

Comparison between .remove() and discard()

.remove() returns an error if the key is not present

st.remove('guava') # error

Output:

---------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-15-d4a7a1e64fd5> in <module>()
----> 1 st.remove('guava')
KeyError: 'guava'

.discard()` does not return an error

st.discard('guava') #no error

Set Operations

st1 = {0, 1, 2, 3, 4}
st2 = {3, 4, 5, 6, 7, 8}
# Union
# return elements in st1 and st2 without duplicate
print(st1|st2)
print(st1.union(st2))
# Intersection
# returns elements present in both st1 and st2 without #duplicates
print(st1 & st2)
print(st1.intersection(st2))
# Difference
# elements in first set but not in second set
print(st1 - st2)
print(st1.difference(st2))

Output:

{0, 1, 2, 3, 4, 5, 6, 7, 8} 
{0, 1, 2, 3, 4, 5, 6, 7, 8}
{3, 4}
{3, 4}
{0, 1, 2}
{0, 1, 2}

Frozen sets

These are immutable sets. It remains the same after its creation

frzn_st = frozenset(["Techno", "mad", "lyf"])
print(frzn_st)
frzn_st.add("forever") #Returns Error

Output:

frozenset({'lyf', 'Techno', 'mad'})--------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-19-d725675c562e> in <module>()
2 print(frzn_st)
3
----> 4 frzn_st.add("forever")
AttributeError: 'frozenset' object has no attribute 'add'

We have discussed different data types over the last few blogs. These are very important with numerous functionality. Hope you understand their uses.

You can refer to:

You can also practice using my colab notebook: