Continuation of Python Data Structures and its benefits

Hello readers, welcome back to know the continuation of Advanced Data Structures in Python. Only three are remaining and they are Strings, Dictionaries, and FrozenSets.

Python Advanced Data Structures Continuation:

If you are new to Python Data Structures, kindly read the previous article to know the Python Data Structures.
Soon will discuss Python Strings, Python Dictionaries, and Python Frozen Sets.

advanced data structures

Python Strings:

One of the curious things about python is that in many ways we can manipulate ‘strings’ in the same way as the lists are manipulated. This makes the strings a kind of convenient data structure to use.  A string is the set of characters wrapped together and assigned to a variable. Initialization, creation, and string operations are shown in the below example.

Highlights of using Strings:

  • We can use  len()  in a string
  • We can find the segments and form substrings
  • we can use the operator  ‘in’  to search the chain
  • There are several very useful methods when it comes to manipulating chains such as  ‘split ()’  which stores the string in an array according to the character that we indicate, or according to the blanks if we do not specify any
>>> len("abrakadabra")
>>> str1 = "helloworld"
>>> str1[1] #first character
>>> str1[-2] #penultimate character
>>> str1[1:5] #characters from 1 to 5
>>> str1[:5] #characters from first to fifth
>>> str1[5:] #characters from the fifth to the last
>>> str1[-2:] # the last two characters from the string
>>> str1[:-2] # the entire string minus two characters
>>> str1[::-1] # reverse the order of the chain
#Use the operator bitwise 'in' to search the chain
>>> 'hell' in 'hello'
>>> 'full' in 'hello'
>>> 'el' in 'hello'
# using split() function with strings
>>> "hello world".split()
['hello', 'world']
>>> "a,b,c".split(',')
['a', 'b', 'c']

If we wanted to rejoin the elements of the arrangement in a  ‘string’  we can use the ‘join’  method.
The strip method removes the character or sequence of characters from the string as indicated.
Python supports formats in its  strings  that remind us of that old and reliable  preparedStatement

>>> " ".join(['hello', 'world'])
'hello world'
# using strip() function 
>>> ' hello world\n'.strip()
'hello world'
>>> 'abcdefgh'.strip('abdh')
# prepared statements
>>> a = 'hello'
>>> b = 'python'
>>> "%s %s" % (a, b)
'hello python'
>>> 'Chapter %d: %s' % (1, 'Data structures')
'Chapter 1: Data structures'

Python Dictionaries:

A dictionary in python acts in a similar way to a list, except that its index does not necessarily have to be an integer number, and they closely resemble a JSON object. The dictionary allows you to associate a part of the data (one “key”) with another (a “value”).

Let us see the declaration of the dictionary and its use:

>>> my_dict = {'x': 1, 'y': 2, 'z': 3}
>>> my_dict['x']
>>> my_dict['z']
>>> dict1 = {}
>>> dict1['x'] = 2
>>> dict1[2] = 'foo'
>>> dict1[(1, 2)] = 3
>>> dict1
{(1, 2): 3, 'x': 2, 2: 'foo'}
# To delete an element from a dictionary, we use the command  of the
>>> my_dict = {'x': 1, 'y': 2, 'z': 3}
>>> del my_dict['x']
>>> my_dict
{'y': 2, 'z': 3}

The method keys() returns all the keys in the dictionary. The ‘values()’ method returns all values within the dictionary, and the ‘items()’ method returns all key-value pairs within the dictionary.

>>> my_dict = {'x': 1, 'y': 2, 'z': 3}
>>> my_dict.keys()
['x', 'y', 'z']
>>> my_dict.values()
[1, 2, 3]
>>> my_dict.items()
[('x', 1), ('y', 2), ('z', 3)]

By using enumerate() function we can retrieve the position of the item index and its corresponding value using loops or looping through a sequence.

>>> for index, value in enumerate(['first_name', 'last_name', 'email_id']):
	print(index, value)
0 first_name
1 last_name
2 email_id

We can also add two or more sequences at the same time using zip() function. Here the values are paired through zip() function by looping.

>>> questions = ['Brand', 'car', 'color']
>>> answers = ['Skoda', 'Rapid', 'blue']
>>> for qstn, ans in zip(questions, answers):
	print('What is the {0}?  It is {1}.'.format(qstn, ans))
What is the Brand?  It is Skoda.
What is the car?  It is Rapid.
What is the color?  It is blue.

# look inside a dictionary with the word  in
>>> my_dict = {'x': 1, 'y': 2, 'z': 3}
>>> 'x' in my_dict
>>> 'p' in my_dict
>>> my_dict.has_key('x')
>>> my_dict.has_key('p')

Likewise, we can obtain an ‘item’ from the list specifically with the method get, and define what to return if the ‘item’ does not exist in the dictionary.

>>> dict1 = {'x': 1, 'y': 2, 'z': 3}
>>> dict1.get('x', 5)
>>> dict1.get('p', 5)
>>> dict1.setdefault('x', 0)
>>> dict1
{'z': 3, 'y': 2, 'x': 1}
>>> dict1.setdefault('p', 0)
>>> dict1
{'p': 0, 'z': 3, 'y': 2, 'x': 1}

Python Frozen Sets:

It is an extension of  Python Sets, but with a different context. As we know Python Sets are mutable whereas Python Frozen Sets are immutable. We can not change the value once it is declared and assigned as shown in the example. Frozen Sets are used only when the values are fixed and can’t be modified.

It accepts only one parameter, that can be a set or dictionary.

>>> string= ('s', 'r', 'i', 'k', 'a', 'n', 't', 'h')
>>> frozenSet = frozenset(string)
>>> print('frozen set is:', frozenSet )
frozen set is: frozenset({'s', 'i', 't', 'a', 'n', 'k', 'h', 'r'})
>>> print('empty frozen set:', frozenset())
empty frozen set: frozenset()

# frozen set using as a dictionary
>>>analyst = {"name": "Doe", "age": 27, "sex": "Male"}
>>>frznSet = frozenset(analyst )
>>>print('The frozen set is:', frznSet)
The frozen set is: frozenset({'age', 'sex', 'name'})