Vikram Chiluka

reverse a number

Write a Program to Reverse a Number in Python | Reverse Digits or Integers

Given a number, thee task is to reverse the given number in Python.

Examples:

Example1:

Input:

number=12345

Output:

The reversed number = 54321

Explanation:

After reversing the number we get 54321

Example2:

Input:

number=7341

Output:

The reversed number = 1437

Example3:

Input:

number=9840

Output:

The reversed number = 489

Explanation:

Here the reversed number is 0489 we neglect the leading zero so the reversed number is 489

Reverse the given Number in Python

There are several ways to reverse the given number in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using while loop

Algorithm:

  • Scan the given number
  • Set the variable reverse_number to 0.
  • Loop while number > 0 Loop while number > 0
  • Multiply reverse_number by 10 and add the remainder to reverse_number like below
  • reverse_number = (reverse_number * 10) + remainder
  • Divide the given number by 10 to remove the last digit.
  • Print the reversed number

Below is the implemenatation:

# given number
given_num = 12345

# Take a variable reverse_number and initialize it to null
reverse_number = 0

# using while loop to reverse the given number

while (given_num > 0):
    # implementing the algorithm
    # getting the last digit
    remainder = given_num % 10
    reverse_number = (reverse_number * 10) + remainder
    given_num = given_num // 10

# Display the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 54321

Method #2: Using for loop and string concatenation

Approach: 

  • Scan the given number.
  • Take a empty string say revstring.
  • Convert the given number to string using str() function.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • Print the revstring.

Below is the implementation:

1)For numbers without trailing zeroes

# given number
given_num = 12345
# taking empty string
reverse_string = ""
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+strnum[index]
# print the result
print("The reversed number =", reverse_string)

Output:

The reversed number = 54321

Note:

Here it gives the correct result as their are no trailing zeroes

Let us consider a case where the given number contains trailing zeroes .

EX: 9840

The above algorithm gives the output

The reversed number = 0489

Here it also prints the leading zeroes so to avoid this the solution is given below.

Solution:

After getting the reversed string convert the string to integer using int() function which removes the leading zeroes

as below.

2)For numbers with trailing zeroes

# given number
given_num = 9840
# taking empty string
reverse_string = ""
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+strnum[index]
# converting the string to integer using int() function
reverse_number = int(reverse_string)
# print the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 489

Method #3:Using Slicing

Approach:

  • Scan the given number.
  • Convert the given number to string using str() function.
  • Reverse the string using slicing
  • Convert this reversed string to integer to avoid leading zeros as mentioned in method #2.
  • Print the reversed string.

Below is the implementation:

# given number
given_num = 9840
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Reversing the string using slicing
reverse_string = strnum[len(strnum)::-1]
# converting the string to integer using int() function
reverse_number = int(reverse_string)
# print the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 489

Method #4:Using list  and join functions

Approach:

  • Scan the given number.
  • Convert the given number to string using str() function.
  • Convert this string to list of digits using list() function.
  • Reverse the list using reverse() function
  • Join the list using join() function to get reversed string.
  • Convert this reversed string to integer to avoid leading zeros as mentioned in method #2.
  • Print the reversed string.

Below is the implementation:

# given number
given_num = 9840
# Convert the given_num to string using str
strnum = str(given_num)
# converting to list of digits
numberslist = list(strnum)
# reverse the list and
numberslist.reverse()
# convert this list to string using join
reverse_string = ''.join(numberslist)
# converting the string to integer using int() function
reverse_number = int(reverse_string)
# print the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 489

Related Programs:

Disarium Number in Python

Disarium Number in Python

Disarium Number:

A Disarium number is one in which the sum of each digit raised to the power of its respective position equals the original number.

like 135 , 89 etc.

Example1:

Input:

number =135

Output:

135 is disarium number

Explanation:

Here 1^1 + 3^2 + 5^3 = 135 so it is disarium Number

Example2:

Input:

number =79

Output:

79 is not disarium number

Explanation:

Here 7^1 + 9^2 = 87 not equal to 79  so it is not disarium Number

Disarium Number in Python

Below are the ways to check Disarium number in python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Using while loop

Algorithm:

  • Scan the number and calculate the size of the number.
  • Make a copy of the number so you can verify the outcome later.
  • Make a result variable (with a value of 0) and an iterator ( set to the size of the number)
  • Create a while loop to go digit by digit through the number.
  • On each iteration, multiply the result by a digit raised to the power of the iterator value.
  • On each traversal, increment the iterator.
  • Compare the result value to a copy of the original number.

Below is the implementation:

# given number
num = 135
# intialize result to zero(ans)
ans = 0
# calculating the digits
digits = len(str(num))
# copy the number in another variable(duplicate)
dup_number = num
while (dup_number != 0):

    # getting the last digit
    remainder = dup_number % 10

    # multiply the result by a digit raised to the power of the iterator value.
    ans = ans + remainder**digits
    digits = digits - 1
    dup_number = dup_number//10
# It is disarium number if it is equal to original number
if(num == ans):
    print(num, "is disarium number")
else:
    print(num, "is not disarium number")

Output:

135 is disarium number

Method #2: By converting the number to string and Traversing the string to extract the digits

Algorithm:

  • Initialize a variable say ans to 0
  • Using a new variable, we must convert the given number to a string.
  • Take a temp count =1 and increase the count after each iteration.
  • Iterate through the string, convert each character to an integer, multiply the ans by a digit raised to the power of the count.
  • If the ans is equal to given number then it is disarium number

Below is the implementation:

# given number
num = 135
# intialize result to zero(ans)
ans = 0
# make a temp count to 1
count = 1
# converting given number to string
numString = str(num)
# Traverse through the string
for char in numString:
    # Converting the character of string to integer
    # multiply the ans by a digit raised to the power of the iterator value.
    ans = ans+int(char)**count
    count = count+1
# It is disarium number if it is equal to original number
if(num == ans):
    print(num, "is disarium number")
else:
    print(num, "is not disarium number")

Output:

135 is disarium number

Related Programs:

Harshad Number in Python

Harshad Number in Python

Harshad Number:

A Harshad number is one whose original number is divisible by the sum of its digits.

like 5 , 18 , 156 etc.

Example 1:

Input:

number=18

Output:

18 is harshad number

Explanation:

Here sum_of_digits=9 i.e (1+8 ) and 18 is divisible by 9

Example 2:

Input:

number=19

Output:

19 is not harshad number

Explanation:

Here sum_of_digits=10 i.e (1+ 9 ) and 19  is not divisible by 10

Harshad Number in Python

Below are the ways to check harshad number in python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Using while loop

Algorithm:

  • Scan the input number
  • Make a copy of the number so you can verify the outcome later.
  • Make a result variable ( set to 0 ).
  • Create a while loop to go digit by digit through the number.
  • Every iteration, increase the result by a digit.
  • Divide the result by the number’s duplicate.
  • If a number divides perfectly, it is a Harshad Number; otherwise, it is not.

Below is the implementation:

# given number
num = 18
# intiialize sum of digits to 0
sum_of_digits = 0
# copy the number in another variable(duplicate)
dup_number = num
# Traverse the digits of number using for loop
while dup_number > 0:
    sum_of_digits = sum_of_digits + dup_number % 10
    dup_number = dup_number // 10
# It is harshad number if sum of digits is equal to given number

if(num % sum_of_digits == 0):
    print(num, "is harshad number")
else:
    print(num, "is not harshad number")

Output:

18 is harshad number

Method #2: By converting the number to string and Traversing the string to extract the digits

Algorithm:

  • Using a new variable, we must convert the given number to a string.
  • Iterate through the string, convert each character to an integer, and add the result to the sum.
  • If a number divides perfectly, it is a Harshad Number; otherwise, it is not.

Below is the implementation:

# given number
num = 18

# Converting the given number to string
numString = str(num)

# intiialize sum of digits to 0
sum_of_digits = 0

# Traverse through the string
for char in numString:
  # Converting the character of string to integer and adding to sum_of_digits
    sum_of_digits = sum_of_digits + int(char)


# It is harshad number if sum of digits is equal to given number

if(num % sum_of_digits == 0):
    print(num, "is harshad number")
else:
    print(num, "is not harshad number")

Output:

18 is harshad number

Method #3: Using list and map

Algorithm:

  • Convert the digits of given number to list using map function.
  • Calculate the sum of digits using sum() function.
  • If a number divides perfectly, it is a Harshad Number; otherwise, it is not.

Below is the implementation:

# given number
num = 18
# Converting the given number to string
numString = str(num)
# Convert the digits of given number to list using map function
numlist = list(map(int, numString))
# calculate sum of list
sum_of_digits = sum(numlist)

# It is harshad number if sum of digits is equal to given number
if(num % sum_of_digits == 0):
    print(num, "is harshad number")
else:
    print(num, "is not harshad number")

Output:

18 is harshad number

Related Programs:

Find the Factorial of a Number

Python Program to Find the Factorial of a Number

Factorial of a number:

The product of all positive integers less than or equal to n is the factorial of a non-negative integer n, denoted by n! in mathematics:

n! = n * (n – 1) *(n – 2) * . . . . . . . . . . 3 * 2 * 1.

4 != 4 * 3 * 2 * 1

Examples:

Input:

number = 7

Output:

Factorial of 7 = 5040

Given a number , the task is to find the factorial of the given number

Finding Factorial of a Number

There are several ways to find factorial of a number in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using for loop(Without Recursion)

Approach:

  • Create a variable say res and assign it to 1.
  • Using for loop and range,  Run a loop from 1 to n.
  • Multiply the res with the loop iterator value.

Below is the implementation:

# given number
num = 7
# initializing a variable res with 1
res = 1
# Traverse from 1 to n
for i in range(1, num+1):
    res = res*i
# print the factorial
print("Factorial of", num, "=", res)

Output:

Factorial of 7 = 5040

Method #2: Using recursion

To find the factorial of a given number, we will use recursion. We defined the factorial(num) function, which returns 1 if the entered value is 1 and 0 otherwise, until we get the factorial of a given number.

Below is the implementation:

# function which returns the factorial of given number
def facto(num):
    if(num == 1 or num == 0):
        return 1
    else:
        return num*facto(num-1)


# given number
num = 7
# passing the given num to facto function which returns the factorial of the number
res = facto(num)
# print the factorial
print("Factorial of", num, "=", res)

Output:

Factorial of 7 = 5040

Method #3 : Using Built in Python functions

Python has a built-in function

factorial (number)

which returns the factorial of given number.

Note: factorial function is available in math module

Below is the implementation:

# import math module
import math
# given number
num = 7
# finding factorial using Built in python function
res = math.factorial(num)
# print the factorial
print("Factorial of", num, "=", res)

Output:

Factorial of 7 = 5040

Related Programs:

Related Programs:

How to Check if a Directory is Empty

Python : How to Check if a Directory is Empty ?

One of Python’s many features is the ability to determine whether or not a directory is empty. The os module can be used to accomplish this. In Python, the OS module has functions for communicating with the operating system. Python’s basic utility modules include OS. This module allows you to use operating system-dependent features on the go. Many functions to communicate with the file system are included in the os and os.path modules.

A directory, also known as a folder, is a grouping of files and subdirectories. The os module in Python contains many useful methods for working with directories (and files as well).

Given a directory the task is to check whether the given _directory is empty or not

Check if a Directory is Empty

The os module in Python has a feature that returns a list of files or folders in a directory.

os.listdir(path='.')

It gives you a list of all the files and subdirectories in the direction you specified.

There are several ways to check whether the directory is empty or not some of them are:

Method #1:Using len() function

The directory is empty if the returned list is empty or has a size of 0.

We can find size using len() function.

If the given then it will print given_directory is empty else given_directory is not empty

Below is the implementation:

# checking if the given directory is empty or not
if len(os.listdir('/home/btechgeeks/posts')) == 0:
    print("given_directory is empty")
else:
    print("given_directory is not empty")

Output:

given_directory is empty

Method #2:Using not operator

If not of given path is true then it will print given_directory is empty

else given_directory is not empty.

Below is the implementation:

# checking if the given directory is empty or not
if not os.listdir('/home/btechgeeks/posts'):
    print("given_directory is empty")
else:
    print("given_directory is not empty")

Output:

given_directory is empty

In exceptional cases, check to see if a directory is empty

There may be times when os.listdir() throws an exception. As an example,

  • If the specified path does not exist.
  • If the given path exists, but it is not a directory.

In both cases, os.listdir() will return an error, so we must check this first before calling os.listdir().

Below is the implementation:

# checking if the given directory is empty or not
# given  directory
given_directory = '/home/btechgeeks/posts'
if os.path.exists(given_directory) and os.path.isdir(given_directory):
    if not os.listdir():
        print("given_directory is empty")
    else:
        print("given_directory is not empty")
else:
    print("given_directory doesn't exists')

Output:

given_directory is empty

Related Programs:

Designing Code for Fibonacci Sequence without Recursion

Designing Code for Fibonacci Sequence without Recursion

Fibonacci sequence:

The Fibonacci sequence is a sequence type in which the sum of the previous two numbers is each consecutive number.

First few Fibonacci numbers are 0 1 1 2 3 5 8 …..etc.

Fibonacci sequence without recursion:

Let us now write code to display this sequence without recursion. Because recursion is simple, i.e. just use the concept,

Fib(i) = Fib(i-1) + Fib(i-2)

However, because of the repeated calculations in recursion, large numbers take a long time.

So, without recursion, let’s do it.

Approach:

  • Create two variables to hold the values of the previous and second previous numbers.
  • Set both variables to 0 to begin.
  • Begin a loop until N is reached, and for each i-th index
    • Print the sum of the previous and second most previous i.e sum= previous + second previous
    • Assign previous to second previous i.e. second previous= previous
    • Assign sum to previous i.e previous=sum

Below is the implementation:

1)C++ implementation of above approach.

#include <iostream>
using namespace std;
int main()
{ // given number
    int n = 10;
    // initializing previous and second previous to 0
    int previous = 0;
    int secondprevious = 0;
    int i;
    // loop till n
    for (i = 0; i < n; i++) {
        // initializing sum to previous + second previous
        int sum = previous + secondprevious;
        cout << sum << " ";
        if (!sum)
            previous = 1;
        secondprevious = previous;
        previous = sum;
    }
    return 0;
}

2)Python implementation of above approach.

# given number
n = 10
# initializing previous and second previous to 0
previous = 0
secondprevious = 0
# loop till n
for i in range(n):
    sum = previous + secondprevious
    print(sum, end=" ")
    if (not sum):
        previous = 1
    # initializing value to previous to second previous
    secondprevious = previous
    previous = sum

Output:

0 1 1 2 3 5 8 13 21 34

Related Programs:

Break keyword – Explained with Examples

Python: Break keyword – Explained with Examples

Break Keyword:

The break statement ends the loop that contains it. Control of the programme is transferred to the statement immediately following the body of the loop.

If the break statement is within a nested loop (a loop within another loop), it will terminate the innermost loop.

Break keyword in Python

We can use break keyword in loops such as while loop and for loop as given below.

1)While loop with break keyword

It can cause a while loop to stop in the middle, even if the condition in the “while statement” remains True.

When the interpreter encounters a break statement, it stops the current loop execution and jumps directly to the code following the loop block.

Example:

Let us use break keyword in while loop .

Let us print all even elements from 1 to n till the number is not divisible by 5.

Below is the implementation:

# given n
n = 100
x = 1
# Using while to iterate till n
while(x <= n):
    # if the x is divisible by 5 then break the loop
    if(x % 5 == 0):
        break
    else:
        print(x)
        # increment the x
        x += 1
print("Break keyword is succesfully executed")

Output:

1
2
3
4
Break keyword is succesfully executed

Explanation:

In the preceding example, the condition in a while statement is True. Because the condition in the ‘while statement’ is always True, this type of loop will iterate over a set of statements indefinitely. We used a break statement to end this loop.

We are printing the value of x and then incrementing it by one in the loop block. Then it determines whether or not x is divisible by 5. When x is divisible by 5, the break statement is invoked. This ends the loop, and control is returned at the end of the while loop.

2)For loop with break Keyword

Example:

Let us use break keyword in for loop .

Given a list and print elements of list till the element of list is not divisible by 2.

Below is the implementation:

# given list
given_list = [4, 2, 8, 4, 1, 3, 7]
# Traverse the list using for loop
for i in range(len(given_list)):
    # if the element is not divisible by 2 then break the loop
    if(given_list[i] % 2 != 0):
        break
    else:
        print(given_list[i])
print("Break keyword executed successfully")

Output:

4
2
8
4
Break keyword executed successfully
Convert Dictionary keys to a List

Convert Dictionary keys to a List in Python

In Python, dictionaries are useful data structures that use keys for indexing. They are an unordered sequence of items (key-value pairs), so the order does not matter. The keys are not able to be changed. Dictionaries, like lists, can hold a variety of data types, including integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.

Given a dictionary ,the task is to convert keys of dictionary to a list.

Examples:

Input:

dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Convert Dictionary keys to a List

There are several ways to convert dictionary keys to a list some of them are:

Method #1:Using list()

A dictionary object is also an iterable object in Python, allowing you to iterate over all of the dictionary’s keys.

In Python, there is a member function called dict.keys that is part of the dictionary class ()

It returns a view object or an iterator that loops through the dictionary’s keys. This object can be used to iterate over existing lists or to create new ones.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert given_dictionary keys  to list
list_of_keys = list(dictionary.keys())
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Method #2:Using List Comprehension

The dictionary class in Python has a function keys() that returns an iterable sequence (dict keys) of all keys in the dictionary. Using the sequence returned by keys(), we can use the list comprehension to iterate over all keysin the dictionary and create a list of keys.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert given_dictionary keys  to list using list comprehension
list_of_keys = [key for key in dictionary.keys()]
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Method #3 :Using unpacking

Unpacking * works for any iterable object, so it is simple to create a list by using it in a list literal because dictionaries return their keys when iterated through.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert given_dictionary keys  to list using args function
list_of_keys = [*dictionary]
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Method #4:Converting only specified keys to list

Assume we want to convert only a subset of the keys in a dictionary to a list. For example, create a list of only the keys in the dictionary with values greater than 500. To accomplish this, we can use an if condition to iterate over pairs of dictionary keys and select only those keys where the condition returns True.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert specified given_dictionary keys to list
list_of_keys = [key for key in dictionary.keys() if dictionary[key] > 500]
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'BTechGeeks']

 
Related Programs:

Convert String to Integer

Python: Convert String to Integer

String:

String is an immutable sequence data type in Python. It’s a string of Unicode characters enclosed by single, double, or triple quotes.

Given a string , the task is to convert the given string to integer.

Convert String to Integer in Python

1)int() function

The int() function returns an integer number from the specified value.

If no arguments are provided, the int() function returns an integer object constructed from a number or string x, or it returns 0.

Syntax:

int(string, base)

Parameters:

string : consists of 1's and 0's   ( or )  The string that contains a number, such as ‘9347' or ‘1734' and so on.
base : (integer value) base of the number.
10 is the default value of base.

Returns :

Returns an integer value in the given base that is the binary string's equivalent.

2)Converting given string in integer

Assume we have a string as a Str object that contains the value ‘28119′. We’ll pass the string to the int() function to convert it to an integer, or int object. Which returns the int object after converting this string to an integer.

Below is the implementation:

# given string value
string_value = '28119'
# converting given string to integer
integer = int(string_value)
# printing the integer value
print(integer)
# printing the type after converting string to integer
print('printing the type of object after converting string to integer', type(integer))

Output:

28119
printing the type of object after converting string to integer <class 'int'>

Explanation:

Because we didn't provide a base argument, the base value 10 was used by default when converting the string to an integer.

3)Converting Binary string to integer

Assume we have a Str object with the string ‘10101′. It contains a number’s binary representation. We’ll pass this string to the int() function along with the base value 2 to convert it to an integer, i.e., an int object. The int() function then converts the binary string to an integer and returns a value of int.

Below is the implementation:

# given binary string value
binary_String = '10101'
# converting given binarystring to integer
integer = int(binary_String, 2)
# printing the integer value
print(integer)

Output:

21

4)Converting Hexadecimal string to integer

Assume we have a Str object with the string ‘0x6DCF’. It contains a number’s hexadecimal representation. We’ll pass this string to the int() function along with the base value 16 to convert it to an integer, i.e., an int object. The int() function then converts the hex string to an integer and returns the object int.

Below is the implementation:

# given hexadecimal string value
hexadecimal_string = '0x6DCF'
# converting given hexadecimal to integer
integer = int(hexadecimal_string, 16)
# printing the integer value
print(integer)

Output:

28111

ValueError will be raised if the base value is not set to 16 with a hex string in the int() function. When converting a hexadecimal string to an int object, always remember to set the base value to 16.

5)Converting octal string to integer

Assume we have a Str object with the string ‘0o103650′. It contains a number’s octadecimal representation. We’ll pass this string to the int() function along with the base value 8 to convert it to an integer, i.e., an int object. The int() function then converts the octadecimal to an integer and returns the object int.

Below is the implementation:

# given octal string value
octal_string = '0o103650'
# converting given octal_string to integer
integer = int(octal_string, 8)
# printing the integer value
print(integer)

Output:

34728

6)Converting a number string with a comma to an integer

We can convert the number string with comma  to integer . By removing all the ‘,’ from the string by replacing the ‘,’ with empty character and then we can use int() to convert it to integer.

Below is the implementation:

# given string
given_string = '2803,11,02'
# replacing the , with empty charcater using replace() function
given_string = given_string.replace(',', "")
# converting the string to integer
intvalue = int(given_string)
# print the string
print(intvalue)

Output:

28031102

Related Programs:

Loop Iterate over all values of Dictionary

Loop / Iterate over all Values of Dictionary in Python

In Python, dictionaries are useful data structures that use keys for indexing. They are an unordered sequence of items (key-value pairs), so the order does not matter. The keys are not able to be changed. Dictionaries, like lists, can hold a variety of data types, including integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.

Given a dictionary, the task is to iterate over all values of the dictionary .

Examples:

Input:

dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}

Output:

600
300
900

Traverse the values of Dictionary

There are several ways to traverse the values of dictionary some of them are:

Method #1:Using for loop

To iterate over the keys of a dictionary, a dictionary object can also be used as an iterable object. We can easily iterate over all keys in the dictionary if we use it with a for loop. The value associated with that key can then be selected during iteration.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using for loop to traverse the dictionary
for key in dictionary:
    print(dictionary[key])

Output:

600
300
900

Method #2:Using  items()

The dictionary class in Python has a function items() that returns an iterable sequence of all the dictionary’s key-value pairs, dict items. It shows all of the dictionary’s items (key-value pairs), so any changes to the original dictionary will be reflected in this sequence. We can’t use indexing with this sequence, either. This can be used in conjunction with a for loop to iterate over all pairs in the dictionary, and we can select the second element of the pair / tuple, i.e. the value, while iterating.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using items()
for key, value in dictionary.items():
    # printing the value
    print(value)

Output:

600
300
900

Method #3:Using values()

The dictionary class in Python has a function values() that returns an iterable sequence of all dictionary values, i.e. dict values. It is a view of the dictionary’s entire value set, which means that any changes to the original dictionary will be reflected in this sequence. We can’t use indexing with this sequence, either. However, we can use this in conjunction with a for loop to iterate through all of the dictionary’s values.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using values()
for value in dictionary.values():
    # printing the value
    print(value)

Output:

600
300
900

Method #4:Using  list Comprehension

This list comprehension can also be used to iterate through all of the dictionary’s values and print each one separately.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using list comprehension
print([value for value in dictionary.values()])

Output:

[600, 300, 900]

Method #5:Converting values to list

The sequence returned by the values() function can be passed to the list to create a list of all values in the dictionary .

We use list() function to achieve this. Print the list(values).

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# converting given dictionary values to list using values() function
list_values = list(dictionary.values())
# print the dictionary values
for value in list_values:
    print(value)

Output:

600
300
900

Related Programs: