Author name: Vikram Chiluka

How to Find the Levenshtein Distance using Enchant in Python?

Enchant Module in Python:

Enchant is a Python module that checks a word’s spelling and provides suggestions for correcting it. The antonyms and synonyms of the words are also provided. It determines whether or not a word is in the dictionary.

What is Levenshtein distance?

The Levenshtein distance between two strings is the minimum number of characters required to insert, delete or replace in a given string str_1 to transform it to another string str_2.

enchant.utils.levenshtein() method:

The enchant.utils.levenshtein() method of the enchant module is used to calculate the Levenshtein distance between two strings.

Syntax:

enchant.utils.levenshtein(str_1, str_2)

Examples:

Example1:

Input:

Given First String = pqr 
Given Second String = pst

Output:

The Levenshtein distance to convert { pqr } to { pst }:
2

Explanation:

To convert given first string { pqr } to { pst } we we should change 
q,r to s, t respectively i.e, 2 characters

Example2:

Input:

Given First String = helloPythonprograms 
Given Second String = hiPythonprograms

Output:

The Levenshtein distance to convert { helloPythonprograms } to { hiPythonprograms }:
4

Finding the Levenshtein Distance using Enchant in Python

Below are the ways to find the Levenshtein distance using enchant in Python:

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import enchant module using the import keyword
  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Calculate the Levenshtein distance (minimum characters required to convert the first string to the second string) between the given two strings using the levenshtein() function by passing the given first and second strings as arguments to it and print the result.
  • The Exit of the Program.

Below is the implementation:

# Import enchant module using the import keyword
import enchant

# Give the first string as static input and store it in a variable.
gvn_str1 = "pqr"
# Give the second string as static input and store it in another variable.
gvn_str2 = "pst"

# Calculate the Levenshtein distance (minimum characters required to convert the first string 
# to second string) between the given two strings using the levenshtein() function
# by passing given first and second strings as arguments to it and print it.
print("The Levenshtein distance to convert {",gvn_str1,"} to {",gvn_str2,"}:")
print(enchant.utils.levenshtein(gvn_str1, gvn_str2))

Output:

The Levenshtein distance to convert { pqr } to { pst }:
2

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import enchant module using the import keyword
  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Calculate the Levenshtein distance (minimum characters required to convert the first string to the second string) between the given two strings using the levenshtein() function by passing the given first and second strings as arguments to it and print the result.
  • The Exit of the Program.

Below is the implementation:

# Import enchant module using the import keyword
import enchant

# Give the first string as user input using the input() function and store it in a variable.
gvn_str1 = input("Enter some random first string = ")
# Give the second string as user input using the input() function and store it in another variable.
gvn_str2 = input("Enter some random second string = ")

# Calculate the Levenshtein distance (minimum characters required to convert the first string 
# to the second string) between the given two strings using the levenshtein() function
# by passing given first and second strings as arguments to it and print it.
print("The Levenshtein distance to convert {",gvn_str1,"} to {",gvn_str2,"}:")
print(enchant.utils.levenshtein(gvn_str1, gvn_str2))

Output:

Enter some random first string = helloPythonprograms
Enter some random second string = hiPythonprograms
The Levenshtein distance to convert { helloPythonprograms } to { hiPythonprograms }:
4

 

 

How to Find the Levenshtein Distance using Enchant in Python? Read More »

Chunking Text using Enchant in Python

Enchant Module in Python:

Enchant is a Python module that checks a word’s spelling and provides suggestions for correcting it. The antonyms and synonyms of the words are also provided. It determines whether or not a word is in the dictionary.

To tokenize text, Enchant also provides the enchant.tokenize module. Tokenizing is the process of separating/splitting words from the body of a text. However, not all words must be tokenized at all times. Assume we have an HTML file; upon tokenization, all tags will be included. Typically, HTML tags do not contribute to the content of the article, so there is a need to tokenize by excluding them.

HTMLChunker is the only chunker that is currently implemented here.

In simple words, here we exclude the HTML Tags during the Tokenization.

Chunking Text using Enchant in Python

Approach:

  • Import get_tokenizer function from the enchant.tokenize module using the import keyword
  • Import HTMLChunker function from the enchant.tokenize module using the import keyword
  • Give the text with HTML tags to be tokenized as static input and store it in a variable.
  • Pass the language code as an argument to the get_tokenizer() function to get the tokenizer class and store it in another variable.
  • Take an empty list to store the tokens.
  • Printing the tokens of the given text without chunking
  • Loop in each word of the token text by passing the given text as an argument to the tokenizer using the for loop
  • Add/append the token words to the newly created list using the append() function
  • Print the token list(It prints the tokens with the position without chunking)
  • Here chunking means excluding the HTML tokens
  • Pass the language code, type of chunkers(HTMLChunker) as an argument to the get_tokenizer() function to get the tokenizer class with chunk(HTML Chunking) and store it in another variable.
  • Take an empty list to store the tokens with chunking.
  • Printing the tokens of the given text after chunking
  • Loop in each word of the token text with chunking by passing the given text as an argument to tokenizer_withchunking using the for loop
  • Add/append the token words with chunking to the newly created chunking list using the append() function
  • Print the token list with chunking(It prints the tokens with the position with HTML chunking)
  • Here HTML chunking means excluding the HTML tags while tokenization.
  • The Exit of the Program.

Below is the implementation:

# Import get_tokenizer function from the enchant.tokenize module using the import keyword
from enchant.tokenize import get_tokenizer
# Import HTMLChunker function from the enchant.tokenize module using the import keyword
from enchant.tokenize import HTMLChunker

# Give the text with HTML tags to be tokenized as static input and store it in a variable.
gvn_txt = "<div> <h2> welcome to Python-programs </h2> <br> </div>"

# Pass the language code as an argument to the get_tokenizer() function to 
# get the tokenizer class and store it in another variable.
tokenizer = get_tokenizer("en_US")

# Take an empty list to store the tokens.
tokens_lst =[]

# Printing the tokens of the given text without chunking
print("The tokens of the given text without chunking:")
# Loop in each words of the token text by passing the given text as argument to tokenizer using the for loop
for wrds in tokenizer(gvn_txt):
    # Add/append the token words to the newly created list using the append() function
    tokens_lst.append(wrds)
    
# Print the token list(It prints the tokens with the position without chunking) 
# Here chunking means excluding the HTML tokens
print(tokens_lst)

 
# Pass the language code, type of chunkers(HTMLChunker) as an argument to the get_tokenizer() function to 
# get the tokenizer class with chunk(HTML Chunking) and store it in another variable.
tokenizer_withchunking = get_tokenizer("en_US", chunkers = (HTMLChunker, ))
print()

# Take an empty list to store the tokens with chunking
tokenslist_chunk = []

# Printing the tokens of the given text after chunking
print("The tokens of the given text after chunking:")

# Loop in each words of the token text with chunking by passing the given text as argument to tokenizer_withchunking
# using the for loop
for wrds in tokenizer_withchunking(gvn_txt):
     # Add/append the token words with chunking to the newly created chunking list using the append() function
    tokenslist_chunk.append(wrds)

# Print the token list with chunking(It prints the tokens with the position with HTML chunking) 
# Here HTML chunking means excluding the HTML tags while tokenization
print(tokenslist_chunk)

Output:

The tokens of the given text without chunking:
[('div', 1), ('h', 7), ('welcome', 11), ('to', 19), ('Python', 22), ('programs', 29), ('h', 40), ('br', 45), ('div', 51)]

The tokens of the given text after chunking:
[('welcome', 11), ('to', 19), ('Python', 22), ('programs', 29)]

Chunking Text using Enchant in Python Read More »

How to Convert Dictionary to a String in Python?

Dictionary in Python:

A dictionary is a Python object that stores data in the key:value format. A colon(:) separates the key and its corresponding value. A comma (,) separates each key:value pair in the dictionary.  In Python, a dictionary is always enclosed in curly brackets.

A Python dictionary, unlike a list or a tuple, is an unordered data structure. We can directly access any value in a Python dictionary by using the key that corresponds to it.

Converting Dictionary to a String in Python

In Python, there are various methods for converting a dictionary to a string.

The most common methods are as follows:

Method #1: Using str() Function

The str() method is a very simple method to convert a dictionary to a string. The resulting string contains all of the dictionary’s keys, values, colon, and even curly braces.

Syntax:

str(dict)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Print the given original dictionary
  • Print the datatype of the given original dictionary using the type() function
  • Convert the given dictionary to string using the str() function by passing the given dictionary as an argument to it.
  • Store it in another variable.
  • Print the given dictionary after conversion to string.
  • Print the datatype of the given dictionary after conversion using the type() function.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {"hello": 10 ,"Python": 20 ,"programs": 30}
# Print the given original dictionary
print("The given original dictionary = ", gvn_dict)
# Print the datatype of the given original dictionary using the type() function
print("The datatype of the given original dictionary = ", type(gvn_dict))
print()

# Convert the given dictionary to string using the str() function by passing 
# given dictionary as an argument to it.
# Store it in another variable.
str_conversion =str(gvn_dict)
# Print the given dictionary after conversion to string.
print("The given dictionary after conversion to string = ", str_conversion)
# Print the datatype of the given dictionary after conversion using the type() function
print("The datatype of the given dictionary after conversion = ", type(str_conversion))

Output:

The given original dictionary = {'hello': 10, 'Python': 20, 'programs': 30}
The datatype of the given original dictionary = <class 'dict'>

The given dictionary after conversion to string = {'hello': 10, 'Python': 20, 'programs': 30}
The datatype of the given dictionary after conversion = <class 'str'>

Method #2: Using for loop and join() Function

To convert a dictionary to a string, we use the join() method of string and a for loop here. The join method concatenates all of the elements of an iterable into a single string.

Syntax: 

str_seperator.join(iterable)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Print the given original dictionary
  • Print the datatype of the given original dictionary using the type() function
  • Add all the key and values of the dictionary using list comprehension and convert them to a string using the join() function.
  • Store it in another variable.
  • Print the given dictionary after conversion to string.
  • Print the datatype of the given dictionary after conversion using the type() function.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {"hello": 10 ,"Python": 20 ,"programs": 30}
# Print the given original dictionary
print("The given original dictionary = ", gvn_dict)
# Print the datatype of the given original dictionary using the type() function
print("The datatype of the given original dictionary = ", type(gvn_dict))
print()

# Add all the key and values of the dictionary using list comprehension and
# convert them to string using the join() function.
str_conversion = ', '.join(str(key)+':'+str(value) for key, value in gvn_dict.items())

# Print the given dictionary after conversion to string.
print("The given dictionary after conversion to string = ", str_conversion)
# Print the datatype of the given original dictionary using the type() function
print("The datatype of the given dictionary after conversion = ", type(str_conversion))

Output:

The given original dictionary = {'hello': 10, 'Python': 20, 'programs': 30}
The datatype of the given original dictionary = <class 'dict'>

The given dictionary after conversion to string = hello:10, Python:20, programs:30
The datatype of the given dictionary after conversion = <class 'str'>

Method #3: Using json.dumps() Function

JSON is a JavaScript Object Notation that typically stores data as key-value pairs.

The json.dumps() method converts Python dictionaries object into serialized JSON string objects.

By passing the given dictionary to the json.dumps() method, it returns the result as a string.

Syntax:

json.dumps(dict)

Approach:

  • Import json module using the import keyword
  • Give the dictionary as static input and store it in a variable.
  • Print the given original dictionary
  • Print the datatype of the given original dictionary using the type() function
  • Pass the given dictionary to the dumps() method of the json module to convert the given dictionary to a string.
  • Print the given dictionary after conversion to string.
  • Print the datatype of the given original dictionary using the type() function.
  • The Exit of the Program.

Below is the implementation:

# Import json module using the import keyword
import json
# Give the dictionary as static input and store it in a variable.
gvn_dict = {"hello": 10 ,"Python": 20 ,"programs": 30}
# Print the given original dictionary
print("The given original dictionary = ", gvn_dict)
# Print the datatype of the given original dictionary using the type() function
print("The datatype of the given original dictionary = ", type(gvn_dict))
print()

# Pass the given dictionary to the dumps() method of the json module
# to convert the given dictionary to a string
str_conversion = json.dumps(gvn_dict)

# Print the given dictionary after conversion to string.
print("The given dictionary after conversion to string = ", str_conversion)
# Print the datatype of the given original dictionary using the type() function
print("The datatype of the given dictionary after conversion = ", type(str_conversion))

Output:

The given original dictionary = {'hello': 10, 'Python': 20, 'programs': 30}
The datatype of the given original dictionary = <class 'dict'>

The given dictionary after conversion to string = {"hello": 10, "Python": 20, "programs": 30}
The datatype of the given dictionary after conversion = <class 'str'>

 

How to Convert Dictionary to a String in Python? Read More »

Python Lambda with if but without else

 Python lambda functions:
An anonymous function in Python is one that is defined without a name.

In Python, normal functions are defined with the def keyword, while anonymous functions are defined with the lambda keyword.

As a result, anonymous functions are also known as lambda functions.

Syntax:

lambda arguments: Expression

Lambda functions can take any number of arguments but can only execute one expression. The expression is evaluated and the result is returned. Lambda functions can be used in any situation where function objects are required.

Lambda with if but without else in Python

Example1: 

Here we are printing the cube value of 3.

cubes = lambda a: a*a*a
print(cubes (3))

Output:

27

Lamba function with only if statement

# Create a lambda function say mod_val which returns the given number 
# if the given number is greater than 0
mod_val = lambda k: k if(k > 0)

# Pass some random number to the above lambda function and print the result
print(mod_val(2))

Output:

File "<ipython-input-5-0f32857d7ac2>", line 3
mod_val = lambda k: k if(k > 0)
^
SyntaxError: invalid syntax

Explanation:

Here, it throws a syntax error, since a lambda function must return 
a value, and this function returns k if k> 0 and does not 
specify what will be returned if k is 0 or negative.

To solve this problem we should give the else part which returns if k is non-positive.

Example3: 

Here it returns a given number since -k i.e, -(-2) = 2

# Lambda Function with if-else statements

# Create a lambda function say mod_val which returns the given number 
# if the given number is greater than 0
mod_val = lambda k: k if(k > 0) else -k

# Pass some random number to the above lambda function and print the result
print(mod_val(-2))

Output:

2

Lambda Function with if-else statements

Here it returns the given number if the given number is greater than 0 else it prints None

# Lambda Function with if-else statements

# Create a lambda function say mod_val which returns the given number 
# if the given number is greater than 0 else it prints None
mod_val = lambda k: k if(k > 0) else None

# Pass some random number to the above lambda function and print the result
print(mod_val(2))

Output:

2

Lambda Function with map() function 

Python’s map() function accepts a function and a list.

The function is called with all of the list’s items, and a new list is returned with items returned by that function for each item.

# Give the list as static input and store it in a variable.
gvn_lst = [3, 5, 1, 2]

# Adding 2 to each element of the given list using the lambda(), map() functions
rslt_lst = list(map(lambda k: k + 2 , gvn_lst))

# Print the result list after adding 2 to each  element of the given list
print(rslt_lst)

Output:

[5, 7, 3, 4]

Python Lambda with if but without else Read More »

Python Code Introspection

What is Code Introspection?

The ability to determine the properties of objects at runtime is referred to as introspection.

In Python, every object can have attributes and methods. We can dynamically examine Python objects using introspection. Code Introspection is used to examine classes, methods, objects, modules, and keywords in order to obtain information about them so that we can use it. Introspection reveals useful information about the objects in your program.

Python, as a dynamic, object-oriented programming language, supports extensive introspection. Python’s support for introspection is extensive and widespread.

In Python, there are numerous built-in methods for introspection. They are:

  • type()
  • help()
  • dir()
  • id()
  • str()
  • hasattr()
  • repr()
  • callable()
  • issubclass()
  • isinstance()
  • __doc__
  • __name__

Some of these are explained below

Code Introspection in Python

1)type()

The type of object passed as a parameter is returned by this type() function.

# Import sys module using the import keyword
import sys
# Printing the type of given sys module using the type() function
print(type(sys))

# Printing the type of given number using the type() function
gvn_num = 80.45
print(type(gvn_num))

# Printing the type of given tuple using the type() function
gvn_tuple = (9, 7, 3)
print(type(gvn_tuple))

Output:

<class 'module'>
<class 'float'>
<class 'tuple'>

2)help()

The help() function is used to return the documentation for an object. It contains information about what functions do in the program.

# Get the information about the list using the help() function
help(list)

Output:

Help on class list in module builtins:

class list(object)
| list(iterable=(), /)
| 
| Built-in mutable sequence.
| 
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
| 
| Methods defined here:
| 
| __add__(self, value, /)
| Return self+value.
|   ........................................
...................................................
...................................

| Static methods defined here:
| 
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
| 
| ----------------------------------------------------------------------
| Data and other attributes defined here:
| 
| __hash__ = None

3)dir()

The dir() is a built-in function of python that returns a list of attributes and methods for an object.

# Printing all the attributes and methods of the given list using the dir() function
gvn_lst = [8, 3, 6]

print(dir(gvn_lst))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

4)id()

The id() is a built-in function of python that returns the id of an object. During the lifetime of a Program, this id is unique for each object.

gvn_num = 50
# Printing the id of given number using the id() function
print("Id of given number = ", id(gvn_num))

gvn_lst = [8, 3, 6]
# Printing the id of given list using the id() function
print("Id of given list = ", id(gvn_lst))

Output:

Id of given number = 94902631075872
Id of given list = 140049922213520

5)str()

The str() function is used to convert the objects that are passed to it into strings.

# Give the list as static input and store it in a variable.
gvn_num = 50
# Convert the given number into string using the str() function
gvn_num = str(gvn_num)
# Print the type of given number after converting into string using the type() function
print("Printing type of given number after converting into string = ", type(gvn_num))

# Similarly do the same for tuple
gvn_tuple  = (5, 1, 7)
gvn_tuple = str(gvn_tuple)
print("Printing type of given tuple after converting into string = ", type(gvn_tuple))

Output:

Printing type of given number after converting into string = <class 'str'>
Printing type of given tuple after converting into string = <class 'str'>

Python Code Introspection Read More »

How to Print Quotation Marks in Python?

Python does not allow double quotes within double quotes and single quotes within single quotes, which results in an error. It only enables opposing quotes, such as a double quote within a single quote and a single quote within a double quote.

Invalid quotes:

" "Python-programs" "

' 'Python-programs' '

Python Quotation Marks

1)Double quotes(” “)in Python

Printing double quotes is difficult because it is necessary as part of the syntax to enclose the strings. In this post, we’ll look at how to print these double-quotes using the print statement.

The double-quote will not be printed in the cases below. The first two lines of code will produce no output, while the last will produce an error.

Example1

print(" ")
print(" " " ")

Output:

Explanation:

It doesn't gove any output since double-quotes inside a double-quotes is Invalid

Example2

print(""Python-programs"")

Output:

 File "<ipython-input-12-ba874bef0698>", line 1
print(""Python-programs"")
^
SyntaxError: invalid syntax

So to print the double quotes use the below code

Example3

# Give the doule-quoted string as static input and store it in a variable
gvn_str = '"Welcome to Python-programs"'
# Print the given string
print(gvn_str)

Output:

"Welcome to Python-programs"

2)Single quotes(‘ ‘) in Python

Example1

print(' ')
print('' '')

Output:

Explanation:

It doesn't gove any output since single-quotes inside a single-quotes is Invalid

Example2

# Give the string as static input and store it in a variable
gvn_str = "'Welcome to Python-programs'"
# Print the given string
print(gvn_str)

Output:

'Welcome to Python-programs'

Example3

# Give the string as static input and store it in a variable
gvn_str = "good morning 'Python-programs' hello"
# Print the given string
print(gvn_str)

Output:

good morning 'Python-programs' hello

String variables in Python

String formatting can also be used to print the double quotes as well as any other character that is part of the print syntax.

gvn_str = 'Welcome to Python-programs'
print("\"%s\""% gvn_str )
print('"%s"' % gvn_str )
print("\\%s\\"% gvn_str )
print('"{}"'.format(gvn_str))

Output:

"Welcome to Python-programs"
"Welcome to Python-programs"
\Welcome to Python-programs\
"Welcome to Python-programs"

How to Print Quotation Marks in Python? Read More »

How to Change Case of All Characters in a .txt File in Python

lower() Method:

The lower() method in python returns a string with all characters in lower case. Symbols and numbers are ignored by this method.

upper() Method:

The upper() method in python returns a string with all characters in the upper case. Symbols and numbers are ignored by this method.

Let us take a samplefile.txt as an Example here which contains the following content.

samplefile.txt:

Hello THIS is PYTHON-programs PLATform
GOOd morning All

Converting All Characters in a Text File to Uppercase

Approach:

  • Open some random file in read-only mode by passing filename/path, mode as arguments to it.
  • Read the given file using the read() function and loop through each letter of the text file using the for loop
  • Convert each letter of the given text file to uppercase using the upper() function and store it in a variable.
  • Open some random new file in append mode using the open() function by passing file path, mode as arguments to it.
  • Store it in another variable.
  • Append the above converted uppercase character to the new file using the write() function.
  • The Exit of the Program.

Below is the implementation:

# Open some random file in read-only mode by passing filename/path, mode as arguments to it. 
gvn_file = open('samplefile.txt', 'r')
# Read the given file using read() function and loop through each letter of the text file
# using the for loop
for k in gvn_file.read():
    # Convert each letter of the given text file to uppercase using the upper() function
    # and store it in a variable.
    res = k.upper()
    # Open some random new file in append mode using the open() function by passing file path, 
    # mode as arguments to it. 
    # Store it in another variable.
    output_file = open('output_file', 'a')
    # Append the above converted uppercase character to the new file using the write() function
    output_file.write(res)

Output:

HELLO THIS IS PYTHON-PROGRAMS PLATFORM
GOOD MORNING ALL

Converting All Characters in a Text File to Lowercase

Approach:

  • Open some random file in read-only mode by passing filename/path, mode as arguments to it.
  • Read the given file using the read() function and loop through each letter of the text file using the for loop
  • Convert each letter of the given text file to lowercase using the lower() function and store it in a variable.
  • Open some random new file in append mode using the open() function by passing file path, mode as arguments to it.
  • Store it in another variable.
  • Append the above converted lowercase character to the new file using the write() function.
  • The Exit of the Program.

Below is the implementation:

# Open some random file in read-only mode by passing filename/path, mode as arguments to it. 
gvn_file = open('samplefile.txt', 'r')
# Read the given file using read() function and loop through each letter of the text file
# using the for loop
for k in gvn_file.read():
    # Convert each letter of the given text file to lowercase using the lower() function
    # and store it in a variable.
    res = k.lower()
    # Open some random new file in append mode using the open() function by by passing file path, 
    # mode as arguments to it. 
    # Store it in another variable.
    output_file = open('output_file', 'a')
    # Append the above converted lowercase character to the new file using the write() function
    output_file.write(res)

Output:

hello this is python-programs platform
good morning all

How to Change Case of All Characters in a .txt File in Python Read More »

How to Remove Duplicates from a Dictionary in Python?

The term duplicates mean the elements which are repeated.

When working with Python dictionaries, you may encounter circumstances where there are duplicate values in the dictionary. In some cases, this can be harmful to your software. In this instance, you may need to remove the duplicates from your dictionary.

When working with Python dictionaries, we may encounter a problem in which we need to delete all duplicate values from the dictionary, and we are unconcerned whether some keys are removed in the process. This type of application can be seen in both school programming and day-to-day programming.

The below-given ways can be used to remove duplicates from a dictionary in  python:

  • Using the for loop
  • Using the Dictionary Comprehension method.

Examples:

Example1:

Input:

Given dictionary = {1: 100, 2: 90, 3: 80, 4: 100, 5:80}

Output:

The given dictionary: {1: 100, 2: 90, 3: 80, 4: 100, 5: 80}
The result dictionary after the removal of duplicates: {1: 100, 2: 90, 3: 80}

Example2:

Here, we are printing the value: key format

Input:

Given dictionary = {10:"hello", 20:"Python-programs", 30:"good", 40:"morning", 50:"hello"}

Output:

The given dictionary:
{10: 'hello', 20: 'Python-programs', 30: 'good', 40: 'morning', 50: 'hello'}
The result dictionary after the removal of duplicates:
{'hello': 50, 'Python-programs': 20, 'good': 30, 'morning': 40}

Removing Duplicates from a Dictionary in Python

Below are the method to remove the duplicates from the given dictionary in Python:

Method #1: Using For loop

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Print the given dictionary
  • Take an empty list and store it in aother variable.
  • Create a new empty dictionary and store it in aother variable.
  • Loop in the key, value of the given dictionary using the for loop and the items() functions
  • Check if the corresponding value is not present in the above created new list using the if conditional statement
  • If it is true then append that value to the above list
  • Here it appends the value to the new list if it is a unique element
  • Assign this unique key and value to the new dictionary
  • Print the result dictionary after the removal of duplicates.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict ={1: 100, 2: 90, 3: 80, 4: 100, 5:80}
# Print the given dictionary
print("The given dictionary:",gvn_dict)
# Take an empty list and store it in aother variable.
new_lst =[]
# Create a new empty dictionary and store it in aother variable.
output_dict ={}
# Loop in the key, value of the given dictionary using the for loop and the items() functions
for key, value in gvn_dict.items():
    # Check if the corresponding value is not present in the above created new list using the 
    # if conditional statement
    if value not in new_lst:
        # If it is true then append that value to the above list 
        # Here it appends the value to the new list if it is a unique element
        new_lst.append(value)
        # Assign this unique key and value to the new dictionary
        output_dict[key] = value
# Print the result dictionary after the removal of duplicates
print("The result dictionary after the removal of duplicates:",output_dict)

Output:

The given dictionary: {1: 100, 2: 90, 3: 80, 4: 100, 5: 80}
The result dictionary after the removal of duplicates: {1: 100, 2: 90, 3: 80}

Method #2: Using Dictionary Comprehension method

This is simply a shortcut for the operations described above. Here we print the value first followed by a key.

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Print the given dictionary
  • Create another dictionary with key as values of original dictionary and values as keys of the original dictionary using dictionary comprehension.
  • Print the result dictionary after the removal of duplicates.
  • The Exit of the Program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict ={10:"hello", 20:"Python-programs", 30:"good", 40:"morning", 50:"hello"}
# Print the given dictionary
print("The given dictionary:\n",gvn_dict)
# Create another dictionary with key as values of original dictionary and
# values as keys of the original dictionary using dictionary comprehension
output_dict = {value:key for key, value in gvn_dict.items()}
# Print the result dictionary after the removal of duplicates
print("The result dictionary after the removal of duplicates:\n",output_dict)

Output:

The given dictionary:
{10: 'hello', 20: 'Python-programs', 30: 'good', 40: 'morning', 50: 'hello'}
The result dictionary after the removal of duplicates:
{'hello': 50, 'Python-programs': 20, 'good': 30, 'morning': 40}

 

 

 

How to Remove Duplicates from a Dictionary in Python? Read More »

How to Get Geolocation in Python using GeoPy?

What is Geolocation?

Geolocation refers to a physical location. It identifies and tracks the location of linked electronic devices using various location technologies such as GPS and IP addresses.

Python’s GeoPy module is used for this purpose. When you enter a location name, it returns all info such as the postal code, city, state, and nation, as well as latitudes and longitudes. When we enter the coordinates, it returns the name of the location.

GeoPy is not a built-in Python library. It must be explicitly installed.

Installation:

pip install geopy

Installation in Anaconda:

conda install geopy

Every geolocation service, such as Google Maps or Nominatim, has its own class in geopy.geocoders that are used to abstract the API of the service. We’ll be using Nominatim, a free API service tool, in this case.

Geocodes of some places in India:

Place                                          Latitude                       Longitude

Telangana, India                       17.123184                         79.208824

Kerala, India                             10.850516                         76.271080

Tamil Nadu, India                   11.127123                           78.656891

Getting Geolocation in Python using GeoPy

1)Getting information about the specified location using Location name

Approach:

  • Import Nominatim from geocoders of geopy module using the import keyword
  • Create an object for Nominatim() class by passing some random user_agent as an argument to it.
  • Here user_agent is the app name to which it is provides services.
  • Pass some random location to the geocode() function and apply it on the above location(Nominatim)
  • Here it gives geopy.location.Location object which contains the address and the coordinate
  • Get the address of the above-given location using the address attribute
  • Get the latitude of the above-given location using the latitude attribute
  • Get the longitude of the above-given location using the longitude attribute
  • Get the altitude of the above-given location using the altitude attribute.
  • The Exit of the Program.

Below is the implementation:

# Import Nominatim from geocoders of geopy module using the import keyword 
from geopy.geocoders import Nominatim
# Create an object for Nominatim() class by passing some random user_agent as an argument to it.
# Here user_agent is the app name to which it is provides services.
location = Nominatim(user_agent= "GetLocationdetails")

# Pass some random location to the geocode() function and apply it on the above location(Nominatim)
# Here it gives geopy.location.Location object which contains the address and the coordinate
Locationinfo = location.geocode("Mumbai Maharastra")
# Get the address of the above given location using the address attribute
print("Address = ", Locationinfo.address)
# Get the latitude of the above given location using the latitude attribute
print("Latitude = ", Locationinfo.latitude)
# Get the longitude of the above given location using the longitude attribute
print("Longitude = ", Locationinfo.longitude)
# Get the altitude of the above given location using the altitude attribute
print("Altitude = ", Locationinfo.altitude)

Output:

Address = Mumbai, Mumbai Metropolitan Region, Mumbai Suburban, Maharashtra, India
Latitude = 19.0759899
Longitude = 72.8773928
Altitude = 0.0

2)Getting information about the specified location using Latitudes, Longitudes

Approach:

  • Import Nominatim from geocoders of geopy module using the import keyword
  • Create an object for Nominatim() class by passing some random user_agent as an argument to it.
  • Here user_agent is the app name to which it is provides services.
  • Pass latitudes and longitudes coordinates as arguments to the reverse() function to get the location name and store it in a variable.
  • Get the address of the above-given location using the address attribute.
  • The Exit of the Program.

Below is the implementation:

# Import Nominatim from geocoders of geopy module using the import keyword 
from geopy.geocoders import Nominatim
# Create an object for Nominatim() class by passing some random user_agent as an argument to it.
# Here user_agent is the app name to which it is provides services.
location = Nominatim(user_agent= "GetLocationdetails")

# Pass latitudes and longitudes coordinates as arguments to the reverse() function to get the
# location name and store it in a variable.
loc_name = location.reverse("19.0759899,  72.8773928")
# Get the address of the above given location using the address attribute
print("The Address of the  from the given latitudes and longitudes: ")
print(loc_name.address)

Output:

The Address of the from the given latitudes and longitudes: 
Santa Cruz – Chembur Link Road, Hallow Pul, L Ward, Zone 5, Mumbai, Mumbai Metropolitan Region, Mumbai Suburban, Maharashtra, 400070, India

 

How to Get Geolocation in Python using GeoPy? Read More »

Use of Right Shift “>>” and Left Shift “<<" Operators in Python

In Python, they are Bitwise Operators known as Bitwise left shift(<<) and Bitwise right shift(>>).

What are Operators?

Operators are the special symbols used to do arithmetic and logical computations. Operators are used to alter values and variables. The value on which the operator operates is referred to as the Operand.

Python Shift Operators

The shift operators are used to shift(move) the bits of a number to the left or right. The number is then multiplied or divided by two. In shifting operators, there are two types of shifting Processes.

  • Bitwise Left Shift.
  • Bitwise Right Shift.

Bitwise Left Shift

The Bitwise Left shift shifts/moves the bits of a number to the Left. We use the “left shift”(<<) symbol for this. It multiplies the number of bits by two respectively.

For example, let the number = 3

Its binary form = 0000 0011

0000 0011<<1 bit = 0000 0110 = 6

Example1

Approach:

  • Give the number as static input and store it in a variable
  • Left Shift 1 bit of the given number and print the result.
  • Left Shift 2 bits of the given number and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable
gvn_numb = 3
# Left Shift 1 bit of the given number and print the result
print("The number after left shifting given number by 1 bit:")
print(gvn_numb<<1)
# Left Shift 2 bits of the given number and print the result
print("The number after left shifting given number by 2 bits:")
print(gvn_numb<<2)

Output:

The number after left shifting given number by 1 bit:
6
The number after left shifting given number by 2 bits:
12

Bitwise Right Shift

The Bitwise Right Shift shifts/moves the bits of a number to the right. We use the “right shift”(>>) symbol for this. It divides the number of bits by two respectively.

For example, let the number = 3

Its binary form = 0000 0011

0000 0011>>1 bit = 0000 0001 = 1

Approach:

  • Give the number as static input and store it in a variable
  • Right Shift 1 bit of the given number and print the result.
  • Right Shift 2 bits of the given number and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable
gvn_numb = 3
# Right Shift 1 bit of the given number and print the result
print("The number after Right shifting given number by 1 bit:")
print(gvn_numb>>1)
# Right Shift 2 bits of the given number and print the result
print("The number after Right shifting given number by 2 bits:")
print(gvn_numb>>2)

Output:

The number after Right shifting given number by 1 bit:
1
The number after Right shifting given number by 2 bits:
0

 

Use of Right Shift “>>” and Left Shift “<<" Operators in Python Read More »