Python

Pandas : Find duplicate rows in a Dataframe based on all or selected columns using DataFrame.duplicated() in Python

How to find duplicate rows in a Dataframe based on all or selected columns using DataFrame.duplicate() in Python ?

In this article we will discuss about how we can find duplicate rows in a Dataframe based on all or selected columns using DataFrame.duplicated(). So first let’s know about this duplicated() function then we will see how it actually works.

DataFrame.duplicated()

Python’s Pandas library contains DataFrame class which provides a function i.e. duplicated() that helps in finding duplicate rows based on specific or all columns.

Synatx : DataFrame.duplicated (subset='None', keep='first')

where,

  • subset : It represents single or multiple column labels which will be used for duplication check. If it is not provided then all columns will be checked for finding duplicate rows.
  • keep : It represents the occurrence which needs to be marked as duplicate. Its value can be (first : here all duplicate rows except their first occurrence are returned and it is the default value also, last : here all duplicate rows except their last occurrence are returned and false : here all duplicate rows except occurrence are returned)

Find Duplicate rows based on all columns :

To find all the duplicate rows based on all columns, we should not pass any argument in subset while calling DataFrame.duplicate(). If any duplicate rows found, True will be returned at place of the duplicated rows expect the first occurrence as default value of keep argument is first.

import pandas as sc

# List of Tuples

players = [('MI', 'Surya', 487),

('RR', 'Buttler', 438),

('CSK', 'Jadeja', 456),

('CSK', 'Jadeja', 456),

('KKR', 'Gill', 337),

('SRH', 'Roy', 241),

('DC', 'Rahane', 221),

('CSK', 'Dhoni', 446),

('PK', 'Malan', 298)

]

# To create a DataFrame object

dfObjs = sc.DataFrame(players, columns=['Team', 'Player', 'Runs'])

# To select duplicate rows based on all columns except the first occurrence

dupliRows = dfObjs[dfObjs.duplicated()]

print("Duplicate rows based on all column excluding first occurrence is:")

print(dupliRows)
Output :
Duplicate rows based on all column excluding first occurrence is:
Team  Player  Runs
3  CSK  Jadeja   456


In the above example all duplicate values returned except the first occurrence, because the by default value of keep is first.

Note : If we make keep argument as last then while finding the duplicate rows last occurrence will be ignored.

Find Duplicate Rows based on selected columns :

If we want to find duplicate compare rows on selected column, then we should pass the columns names as argument in duplicate(), which will return the duplicate rows based on passed or selected columns. Similarly in this case also first occurrence is ignored.

#Program :

import pandas as sc

# List of Tuples

players = [('MI', 'Surya', 487),

('RR', 'Buttler', 438),

('DC', 'Pant', 337),

('CSK', 'Dhoni', 456),

('KKR', 'Gill', 337),

('SRH', 'Roy', 241),

('DC', 'Rahane', 337),

('DC', 'Iyer', 337),

('PK', 'Malan', 298)

]

# To create a DataFrame object

dfObjs = sc.DataFrame(players, columns=['Team', 'Player', 'Runs'])

# Select all duplicate rows based on one column

# To select the duplicated rows based on column that is passed as argument

dupliRows = dfObjs[dfObjs.duplicated(['Team','Runs'])]

print("Duplicate Rows based on a selected column are:", dupliRows, sep='\n')
Output :
Duplicate Rows based on a selected column are:
     Team   Player      Runs
6    DC      Rahane    337
7    DC      Iyer          337

By default value of keep is first, so only matched first row is ignored. Here, we have found rows based on selected columns. In this example we have selected  columns (Team and Runs) based on which 3 rows matches i.e

'DC', 'Pant', 337
'DC', 'Rahane', 337
'DC', 'Iyer', 337

Out of which last two rows are displayed and first row is ignored as the keep value is first(default value).

So it returned last two rows as output i.e

'DC', 'Rahane', 337
'DC', 'Iyer', 337

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Find Elements in a Dataframe

Pandas : Find duplicate rows in a Dataframe based on all or selected columns using DataFrame.duplicated() in Python Read More »

R: Set working directory

How to set work directory in R studio ?

In this article we are going to discuss about how we can set work directory R and also we will verify if that directory has been set perfectly or not. So, let’s start exploring the topic.

R is an interpreted programming language which is created by Ross Ihaka and Robert Gentleman. This programming language and open source environment is used for statistical computing, graphical presentation, data analytics and scientific research.

R studio is an  Integrated Development Environment (IDE) which provides free and open source tools for Rn language.

When working with R language sometimes we need to work with external files and for that we have to set that file directory as working directory otherwise the file won’t be accessible.

So, let’s see how we can set a directory as an working directory in R studio.

Setting up a Working Directory in R studio :

Steps to set working directory in R studio.

  1. Go to session menu.
  2. Select set working directory.
  3. Then select Choose Directory.
  4. From there browse the directory.

Set up Working Directory in R using setwd() function :

By using setwd() function we can set the working directory.

Syntax : setwd("D:/R_workingfile")

For example, we have a directory /Users/BtechGeeks and we want to set it as  working directory then we can do it like this

# command to set working directory.
setwd("Users/BtechGeeks")

If the path does not exist :

If you want to set a directory as working directory but that directory does not exist then it will give Error.

For example, a directory /Users/Btech which does not exists but we want to make it working directory.

Then

# Directory does not exist
setwd("/Users/Btech")
# Raising error as directory does not exit
Error in setwd("/Users/Btech") : cannot change working directory

Verifying the current working directory is set in R :

We can use getwd() function to check the current working directory.

If it returns the correct directory then the working directory has been set perfectly.

# It will give the current working directory
getwd()
>> "/Users/BtechGeeks"

R: Set working directory Read More »

Python: Read CSV into a list of lists or tuples or dictionaries | Import csv to list

Read CSV into a list of lists or tuples or dictionaries | Import csv to list in Python.

In this article, we will demonstrate how we can import a CSV into a list, list of lists or a list of tuples in python. We will be using pandas module for importing CSV contents to the list without headers.

Example Dataset :

CSV File name – data.csv

Id,Name,Course,City,Session
21,Jill,DSA,Texas,Night
22,Rachel,DSA,Tokyo,Day
23,Kirti,ML,Paris,Day
32,Veena,DSA,New York,Night

Read a CSV into list of lists in python :

1. Importing csv to a list of lists using csv.reader :

CSV.reader is a python built-in function from the CSV module which will help us read the CSV file into the python. Then passing the reader object into the list() will return a list of lists.

Let’s see the implementation of it.

#Program :

from csv import reader

#Opening the csv file as a list of lists in read mode
with open('data.csv', 'r') as csvObj:
 #The object having the file is passed into the reader
 csv_reader = reader(csvObj)
 #The reader object is passed into the list( ) to generate a list of lists
 rowList = list(csv_reader)
 print(rowList)
Output :
[['Id', 'Name', 'Course', 'City', 'Session'], 
['21', 'Jill', 'DSA', 'Texas', 'Night'], 
['22', 'Rachel', 'DSA', 'Tokyo', 'Day'], 
['23', 'Kirti', 'ML', 'Paris', 'Day'], 
['32', 'Veena', 'DSA', 'New York', 'Night']]

2. Selecting specific value in csv by specific row and column number :

 We can also select particular rows and columns from the CSV file by using Pandas. We have to read the CSV into a dataframe excluding the header and create a list of lists.

Let’s see the implementation of it.

#Program :

import pandas as pd

# Create a dataframe from the csv file
dfObj = pd.read_csv('data.csv', delimiter=',')
# User list comprehension 
# for creating a list of lists from Dataframe rows
rowList = [list(row) for row in dfObj.values]
# Print the list of lists i.e. only rows without the header
print(rowList)
Output :
[[21, 'Jill', 'DSA', 'Texas', 'Night'], 
[22, 'Rachel', 'DSA', 'Tokyo', 'Day'], 
[23, 'Kirti', 'ML', 'Paris', 'Day'], 
[32, 'Veena', 'DSA', 'New York', 'Night']]

3. Using Pandas to read csv into a list of lists with header :

To include the header row, we can first read the other rows like the previous example and then add the header to the list.

Let’s see the implementation of it.

#Program :

import pandas as pd

# Create a dataframe from the csv file
dfObj = pd.read_csv('data.csv', delimiter=',')
# User list comprehension 
# for creating a list of lists from Dataframe rows
rowList = [list(row) for row in dfObj.values]
#Adding the header
rowList.insert(0, dfObj.columns.to_list())
# Print the list of lists with the header
print(rowList)
Output :
[['Id', 'Name', 'Course', 'City', 'Session'], 
[21, 'Jill', 'DSA', 'Texas', 'Night'], 
[22, 'Rachel', 'DSA', 'Tokyo', 'Day'], 
[23, 'Kirti', 'ML', 'Paris', 'Day'], 
[32, 'Veena', 'DSA', 'New York', 'Night']]

Reading csv into list of tuples using Python :

Let’s add the contents of CSV file as a list of tuples. Each tuple will be representing a row and each value in the tuple represents a column value. Just like the way we added the contents into a list of lists from CSV, we will read the CSV file and then pass it into list function to create a list of tuples. The only difference here is the map( ) function that accepts function and input list arguments.

Let’s see the implementation of it.

#Program :

from csv import reader
# open file in read mode
with open('data.csv', 'r') as readerObj:
    # here passing the file object to reader() to get the reader object
    csv_reader = reader(readerObj)
    #Read all CSV files into the tuples
    tuplesList = list(map(tuple, csv_reader))
    # display the list of tuples
    print(tuplesList)
Output :

[('Id', 'Name', 'Course', 'City', 'Session'), ('21', 'Jill', 'DSA', 'Texas', 'Night'), ('22', 'Rachel', 'DSA', 'Tokyo', 'Day'), ('23', 'Kirti', 'ML', 'Paris', 'Day'), ('32', 'Veena', 'DSA', 'New York', 'Night')]

Reading csv into list of tuples using pandas & list comprehension :

We can load the contents of a CSV file into a dataframe by using read_csv( ) . Then using list comprehension we can convert the 2D numpy array into a list of tuples.

Let’s see the implementation of it.

#Program :

import pandas as pd
# Create a dataframe object from the csv file
dfObj = pd.read_csv('data.csv', delimiter=',')
# Create a list of tuples for Dataframe rows using list comprehension
tuplesList = [tuple(row) for row in dfObj.values]
# Print the list of tuple
print(tuplesList)
Output :
[(21, 'Jill', 'DSA', 'Texas', 'Night'), (22, 'Rachel', 'DSA', 'Tokyo', 'Day'), (23, 'Kirti', 'ML', 'Paris', 'Day'), (32, 'Veena', 'DSA', 'New York', 'Night')]

Reading csv into list of dictionaries using python :

We can also read the contents of a CSV file into dictionaries in python where each dictionary in the list will be a row from the CSV file. The CSV file contents are opened in read mode then they are passed into the Dict_reader( ) as a reader object, then it is passed into the list.

Let’s see the implementation of it.

#Program :

from csv import DictReader
# open file in read mode
with open('data.csv', 'r') as readerObj:
    # pass the reader file object to DictReader() to get the DictReader object
    dict_reader = DictReader(readerObj)
    # get a list of dictionaries from dct_reader
    dictList = list(dict_reader)
    # print the list of dict
    print(dictList)
Output :

[OrderedDict([('Id', '21'), ('Name', 'Jill'), ('Course', 'DSA'), ('City', 'Texas'), ('Session', 'Night')]), OrderedDict([('Id', '22'), ('Name', 'Rachel'), ('Course', 'DSA'), ('City', 'Tokyo'), ('Session', 'Day')]), OrderedDict([('Id', '23'), ('Name', 'Kirti'), ('Course', 'ML'), ('City', 'Paris'), ('Session', 'Day')]), OrderedDict([('Id', '32'), ('Name', 'Veena'), ('Course', 'DSA'), ('City', 'New York'), ('Session', 'Night')])]

Python: Read CSV into a list of lists or tuples or dictionaries | Import csv to list Read More »

Python: Open a file using “open with” statement and benefits explained with examples

Opening a file using ‘open with’ statement and benefits in Python.

In this article we will discuss about how to open a file using ‘open with’ statement, how to open multiple files in a single ‘open with’ statement and finally its benefits. So, let’s start the topic.

The need for “open with” statement :

To understand the “open with” statement we have to go through opening a file in python. For that we can make use of the open( ) function that is in-built in python

File.txt-

New File Being Read.
DONE!!
#program :

# opened a file 
fileObj = open('file.txt')
# Reading the file content into a placeholder
data = fileObj.read()
# print file content
print(data)
#close the file
fileObj.close()
Output :
New File Being Read.
DONE!!

In case the file does not exist it will throw a FileNotFoundError .

How to open a file using “open with” statement in python :

#Program :

# opened a file using open-with
with open('file.txt', "r") as fileObj:
    # Reading the file content into a placeholder
    data = fileObj.read()
    # print file content
    print(data)
# Check if file is closed
if fileObj.closed == False:
    print('File is not closed')
else:
    print('File is already closed')
New File Being Read.
DONE!!
File is closed

The with statements created an execution block that will automatically delete any object that was created in the program, in this case even if it was not closed the reader object was deleted that closed the file automatically. This saves us some memory in case we forgot to close the file.

Benefits of calling open() using “with statement” :

  • Fewer chances of bug due to coding error

With “with” statement we don’t have to close the opened file manually. It takes care of that when the compiler goes out of the block and automatically closes file. So it reduces the chances of bugs, lines of code and releases the memory for other operations.

  • Excellent handling in case of exception

If we have used “open-with” statement to open a file, and an exception occurs inside the with block, the file will be closed and the control moves to the except block.

# Python :

# Before handling the exception file will be closed 
try:
    # using "with statement" with open() function
    with open('file.txt', "r") as fileObj:
        # reading the file content
        data = fileObj.read()
        # Division by zero error
        x = 1 / 0
        print(data)
except:
    # handling the exception caused above
    print('Error occurred')
    if fileObj.closed == False:
        print('File is not closed')
    else:
        print('File is closed')
Output :
Error occurred
File is closed
  • Open multiple files in a single “with statement” :

We can use open with statement to open multiple files at the same time. Let’s try reading from one file and writing into another-

# Program :

# Read from file.txt and write in output.txt
with open('output.txt', 'w') as fileObj2, open('file.txt', 'r') as fileObj1:
    data = fileObj1.read()
    fileObj2.write(data)
    # Both the files are automatically close when the control moves out of the with block.

This will generate a “outuput.txt” file that will have the same contents as our old “file.txt”.

Output : 
Output.txt- 
New File Being Read. 
DONE !!

The files will automatically close when the control moves outside the with block.

Python: Open a file using “open with” statement and benefits explained with examples Read More »

Solved- TypeError: dict_keys object does not support indexing

Getting and resolving ‘TypeError: dict_keys object does not support indexing in Python’.

In this article we will discuss about

  • Reason of getting ‘TypeError: ‘dict_keys’ object does not support indexing’
  • Resolving the type error.

So let’s start exploring the topic.

To fetch keys, values or key-value pair from a dictionary in python we use functions like keys(), values() and items() which return view object so that we get a dynamic view on the dictionary entries.

The important point is that when dictionary changes then these views reflects these changes and we can iterate over it also. But when we want to use indexing on these objects then it causes TypeError.

Getting TypeError :

#Program :

# Dictionary created of string and int
word_freq = {
    'Aa' : 56,
    "Bb"    : 23,
    'Cc'  : 43,
    'Dd'  : 78,
    'Ee'   : 11
}

# Here, fetching a view object 
# by pointing to all keys of dictionary
keys = word_freq.keys()
print('dict_keys view object:')
print(keys)
print('Try to perform indexing:')

# Here, trying to perform indexing on the key's view object 
# Which will cause error
first_key = keys[0]
print('First Key: ', first_key)
Output :

Try to perform indexing:
Traceback (most recent call last):
File “temp.py”, line 18, in <module>
first_key = keys[0]
TypeError: ‘dict_keys’ object does not support indexing

Here, in the above example we got Type error as because we tryied to select value at index 0 from the dict_keys object, which is a view object and we know view object does not support indexing.

Resolving TypeError :

The solution to TypeError: dict_keys object does not support indexing is very simple. We just need to convert these view object dict_keys into a list and then we can perform indexing on that. Means we will cast the dict_keys object to list object and then selecting elements at any index position.

#Program :

# Dictionary created
word_freq = {
    'Aa' : 10,
    "Bb" : 20,
    'Cc' : 30,
    'Dd' : 40,
    'ee' : 50
}
# Here, fetching a view object 
# by pointing to all keys of dictionary
keys = list(word_freq.keys())
print('List of Keys:')
print(keys)

# Selecting 1st element from keys list
first_key = keys[0]
print('First Key: ', first_key)
Output :
List of Keys:
['Aa', 'Bb', 'Cc', 'Dd', 'Ee']
Second Key: Aa
In this example we converted all the keys of the dictionary to list and then we selected 1st element from the list which is present at index position 0 and it also returned the first key which is present at index position 0.

Solved- TypeError: dict_keys object does not support indexing Read More »

How to Create Multi Line String Objects

How to Create Multi Line String Objects in Python ?

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to discuss how to create multi line string objects in python.

Create and Convert Multi Line String Objects in Python

Creating multi line string objects:

Converting multi line string objects to single line objects:

Method #1:Using triple quotes

We can assign the multi-line string to a string variable by enclosing it in triple quotes, i.e. either <> or It will be saved in the same multi-line format as before.

Below is the implementation:

# creating multi line string
multistring = '''Hello this is
               BTechGeeks python
               new learning platform'''
# printing the string
print(multistring)

Output:

Hello this is
               BTechGeeks python
               new learning platform

Creating single line string from multi line string

Method #1:Using brackets

If we want to create a string object from multiple long lines but keep them all in a single line, we should use brackets.

Below is the implementation:

# creating single line string from multi line string
singlestring = ("Hello this is "
                "BTechGeeks python "
                "new learning platform")
# printing the string
print(singlestring)

Output:

Hello this is BTechGeeks python new learning platform

Method #2:Using Escape( \ ) symbol

We can also use the escape character to create a single line string object from a long string of multiple lines.

Below is the implementation:

# creating single line string from multi line string
singlestring = "Hello this is "\
    "BTechGeeks python "\
    "new learning platform"
# printing the string
print(singlestring)

Output:

Hello this is BTechGeeks python new learning platform

Method #3:Using join()

We can also make a single line string object by joining several lines together.

Below is the implementation:

# creating single line string from multi line string
singlestring = ''.join(
    ("Hello this is "
     "BTechGeeks python "
     "new learning platform"))
# printing the string
print(singlestring)

Output:

Hello this is BTechGeeks python new learning platform

Related Programs:

How to Create Multi Line String Objects in Python ? Read More »

Convert Dictionary to List of Tuples Pairs

Python: Convert Dictionary to List of Tuples/ Pairs

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Examples:

Input:

dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}

Output:

[('This', 100), ('is', 200), ('BTechGeeks', 300)]

Convert Dictionary to List of Tuples/ Pairs

There are several ways to convert dictionary to list of tuples/pairs some of them are:

Method #1:Using zip() function

The zip function combines the parameters passed to it. So we pass the dictionary’s keys and values as parameters to the zip function, and the result is passed to a list function. The key-value pair is converted into a list of tuples.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary to list of tuples
listtuple = list(zip(dictionary.keys(), dictionary.values()))
# print list of tuples
print(listtuple)

Output:

[('This', 100), ('is', 200), ('BTechGeeks', 300)]

Method #2:Using items()

The dictionary class in Python includes the items() function, which returns an iterable sequence (dict items) of all key-value pairs in the dictionary. This retuned sequence is a representation of the dictionary’s actual key-value pairs. To get a list of tuples, we can pass this iterable sequence to the list() function.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary to list of tuples
listtuple = list(dictionary.items())
# print list of tuples
print(listtuple)

Output:

[('This', 100), ('is', 200), ('BTechGeeks', 300)]

Method #3:Using List Comprehension

dict.items() returns an iterable sequence of all dictionary key-value pairs. We may use a list comprehension to iterate over this sequence and create a list of tuples. The ith tuple in this list of tuples represents the ith dictionary key-value pair.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary to list of tuples using list comprehension
listtuple = [(key, value) for key, value in dictionary.items()]
# print list of tuples
print(listtuple)

Output:

[('This', 100), ('is', 200), ('BTechGeeks', 300)]

Method #4:Using for loop and append() functions

We can start with an empty list of tuples and then use a for loop to iterate over all key-value pairs in the dictionary, adding each key-value pair to the list one by one.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# creating empty list
listtuple = []
# using for loop to traverse the dictionary
for key in dictionary:
    # append key and value to list as a tuple
    listtuple.append((key, dictionary[key]))

# print list of tuples
print(listtuple)

Output:

[('This', 100), ('is', 200), ('BTechGeeks', 300)]

Related Programs:

Python: Convert Dictionary to List of Tuples/ Pairs Read More »

String isupper() Method

Python String isupper() Method

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to discuss about isupper() method

String isupper() method in Python

1)isupper() method

If all of the characters are in upper case, the isupper() method returns True otherwise, it returns False.

Only alphabet characters are checked, not numbers, symbols, or spaces.

Syntax:

given_string.isupper()

Parameters:

No parameters are passed

Return:

If all cased characters in the string are uppercase and there is at least one cased character, this method returns true; otherwise, it returns false.

Examples:

2)Checking if given string is an uppercase or not

Using the isuuper() function, we can determine whether a string is uppercase or lowercase. If all of the string characters are upper case, the function isupper() returns True.

Below is the implementation:

# given string
string = "BTECHGEEKS"
# determining whether the given string is uppercase
if(string.isupper()):
    print("Given string is in uppercase")
else:
    print("Given string is not in uppercase")

Output:

Given string is in uppercase

EX-2)

# given string
string = "Btechgeeks"
# determining whether the given string is uppercase
if(string.isupper()):
    print("Given string is in uppercase")
else:
    print("Given string is not in uppercase")

Output:

Given string is not in uppercase

3)Checking if given number string is an uppercase or not

Assume we have a string that only contains numbers. Let’s use isupper to see if this string is uppercase or not ().

Below is the implementation:

# given string
string = "28112001"
# determining whether the given string is uppercase
if(string.isupper()):
    print("Given string is in uppercase")
else:
    print("Given string is not in uppercase")

Output:

Given string is not in uppercase

4)Checking if given string containing letters and numbers an uppercase or not

Assume we have a string that contains numbers and uppercase letters. Let’s use isupper to see if this string is uppercase or not ()

Below is the implementation:

# given string
string = "BTECH-28112001"
# determining whether the given string is uppercase
if(string.isupper()):
    print("Given string is in uppercase")
else:
    print("Given string is not in uppercase")

Output:

Given string is in uppercase

Explanation:

As string contains one or more upper case characters but no lower case characters. As a result, isupper() returned True.

5)Checking if given character is in uppercase or not

Individual characters have no data type in Python. A python string object can also be a single character. As a result, we can use the isupper() method to determine whether a character is upper case or not.

Below is the implementation:

# given string
string = "S"
# determining whether the given string is uppercase
if(string.isupper()):
    print("Given char is in uppercase")
else:
    print("Given char is not in uppercase")

Output:

Given char is in uppercase

 
Related Programs:

Python String isupper() Method Read More »

Print Specific Key-Value Pairs of Dictionary

Python: Print Specific Key-Value Pairs of Dictionary

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Given a dictionary, the task is to print specific key-value pairs of the Dictionary.

Display Specific Key-Value Pairs of Dictionary

Indexing:

Dictionary’s items() function returns an iterable sequence of dictionary key-value pairs, i.e. dict items. However, this is a view-only sequence, and we cannot use indexing on it. So, if we want to use indexing to select items from a dictionary, we must first create a list of pairs from this sequence.

We can convert dictionary items to list using list() function

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# using indexing we can print the first key value pair of dictionary
print("1st key value pair :", dictlist[0])

Output:

1st key value pair : ('this', 200)

We can print last key value pair of dictionary using negative indexing(-1) or using length function of list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# using indexing we can print the last key value pair of dictionary
print("last key value pair :", dictlist[-1])

Output:

last key value pair : ('BTechGeeks', 300)

We can print nth key-value pair using indexing

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given n
n = 2
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# using indexing we can print the nth key value pair of dictionary
print("nth key value pair :", dictlist[n-1])

Output:

nth key value pair : ('is', 100)

4)Printing specific key-value pairs based on given conditions

To print specific dictionary items that satisfy a condition, we can iterate over all dictionary pairs and check the condition for each pair. If the condition returns True, then print the pair otherwise, skip it.

Let us print all the key-value pairs whose value is greater than 100

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# Traverse the dictionary
for key, value in dictionary.items():
    # if the value is greater than 100 then print it
    if(value > 100):
        print(key, value)

Output:

this 200
BTechGeeks 300

Related Programs:

Python: Print Specific Key-Value Pairs of Dictionary Read More »

Remove Elements from a List while Iterating

Python: Remove Elements from a List while Iterating

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Example:

Input:

givenlist = ["hello", "this", "is", "this", "BTechGeeks", "this", "python"]

Output:

['hello', 'is', 'BTechGeeks', 'python']

Delete Elements from a List while Iterating

There are several ways to remove elements from the list while iterating some of them are:

Method #1:Using for in loop

To accomplish this, we must first make a copy of the list, and then iterate over that copied list. Then, for each element, we’ll decide whether or not to delete it. If so, use the remove() function to remove that element from the original list.

Below is the implementation:

# given list
givenlist = ["hello", "this", "is", "this", "BTechGeeks", "this", "python"]
# given element which should be deleted
key = "this"
for element in list(givenlist):
    # checking if the element is equal to given key
    if(element == key):
        # using remove to remove element from list
        givenlist.remove(element)
# print the list
print(givenlist)

Output:

['hello', 'is', 'BTechGeeks', 'python']

Method #2:Using List Comprehension

Using list comprehension, we can iterate over the list and choose which elements to keep in the new list. The new list can then be assigned to the same reference variable that was part of the original list.

Below is the implementation:

# given list
givenlist = ["hello", "this", "is", "this", "BTechGeeks", "this", "python"]
# given element which should be deleted
key = "this"
# using list comprehension to remove given element from the list
givenlist = [element for element in givenlist if element != key]
# print the list
print(givenlist)

Output:

['hello', 'is', 'BTechGeeks', 'python']

Method #3:Using filter() function

The Filter() function takes two arguments,

The first is a Lambda function, which can be any function.
The second list is the one from which we want to remove elements.
It iterates through all of the list’s elements, applying the given function to each one. It returns the elements for which the given function returns True during iteration. So we can use the filter() function to iteratively filter elements from a list.

Below is the implementation:

# given list
givenlist = ["hello", "this", "is", "this", "BTechGeeks", "this", "python"]
# given element which should be deleted
key = "this"
# using filter() function to remove given element from the list
givenlist = list(filter(lambda element: element != key, givenlist))
# print the list
print(givenlist)

Output:

['hello', 'is', 'BTechGeeks', 'python']

Related Programs:

Python: Remove Elements from a List while Iterating Read More »