
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum ASCII Values Using Map Function and Dictionary in Python
In this article, we are going to learn how to use the map() function along with dictionaries to add the ASCII values of characters in the string.
The Python built-in ord() function returns the ASCII integer value of a character. Additionally, dictionaries (dict) in Python are used to store key-value pairs.
We use them to associate strings with their total ASCII values, making it easy to store and retrieve the result. Before diving into the examples, let's have a quick look at the Python map() function and the Python ord() function.
Python map() Function
The Python map() function is a built-in function used to transform each item from an iterable with the help of a process known as mapping.
It applies the function on every item in the iterable and returns the map object. Following is the syntax of the Python map() function -
map(function, iterableObject)
Using Python ord() Function
The Python ord() function is used to retrieve the integer representing the Unicode code point of a given character. Unicode code points are the unique numbers assigned to each character in the Unicode standard.
Syntax
Following is the syntax of the Python ord() function -
ord(ch)
Example 1
In this scenario, we are using the map() function and passing the argument ord() function. As a result, it will result in all the characters in the string with ASCII values and applying the sum() function to add them up.
Let's look at the following example, where we are going to get the ASCII values of characters in the string "Welcome" using the map() and sum() functions.
str1 = "Welcome" result = sum(map(ord, str1)) print(" ", result)
The output of the above program is as follows -
716
Example 2
In this case, we are using the dictionary along with the list comprehension for iterating through each character and applying the map() function passed with an argument to get the ASCII values of the characters.
Consider the following example, where we are going to store multiple strings in the dictionary and add the ASCII values.
str1 = ["audi", "bmw", "ciaz"] result = {word: sum(map(ord, word)) for word in str1} print(result)
The output of the above program is as follows -
{'audi': 419, 'bmw': 326, 'ciaz': 423}