Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Convert Dictionary Object into String
Next article icon

Combine similar characters in Python using Dictionary Get() Method

Last Updated : 14 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Let us see how to combine similar characters in a list. 

Example :

Input : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’] 

Output : [‘gg’, ‘eeee’, ‘kk’, ‘ss’, ‘f’, ‘o’, ‘r’]

We will be using the get() method of the dictionary class.

dictionary.get()

The get() method returns the value of the item with the specified key.

Syntax : dictionary.get(key name, value) 

Parameters :

  • keyname : The key name of the dictionary item.
  • value : (Optional) If the specified key does not exist, then a value is returned.

Returns : Value of the item with the specified key

Algorithm :

  1. Declare the list.
  2. Declare a dictionary.
  3. Iterate over the list, using the get() method, if a new key is found, then the value 0 is assigned to it and 1 is added making the final value 1. Else if the key is repeated, then 1 is added to the previously calculated value. So this way, now each key has a value assigned to it, and frequency of all characters is recorded.
  4. Separate all the keys and the values and store them in 2 different lists.
  5. Use the zip() function store the product of keys and their respective values in the result list.
  6. Display the result.

Example 1 : 

python3




# declaring the list of characters
mylist = ['g', 'e', 'e', 'k', 's', 'f',
          'o', 'r', 'g', 'e', 'e', 'k', 's']
 
# declaring the dictionary
dictionary = {}
 
# counting the frequency of the keys
for key in mylist:
    dictionary[key] = dictionary.get(key, 0) + 1
 
# storing the of keys and values
k = list(dictionary.keys())
v = list(dictionary.values())
 
# declaring the result list
result = []
 
# storing the product of keys and
# their respective values in result
for i, j in zip(k, v):
    result.append(i * j)
     
# displaying the result
print(result)
 
 

Output :

['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r']

Example 2 : 

python3




# declaring the list of characters
mylist = ['p', 'y', 't', 'h', 'o', 'n', 't',
          'u', 't', 'o', 'r', 'i', 'a', 'l']
 
# declaring the dictionary
dictionary = {}
 
# counting the frequency of the keys
for key in mylist:
    dictionary[key] = dictionary.get(key, 0) + 1
 
# storing the of keys and values
k = list(dictionary.keys())
v = list(dictionary.values())
 
# declaring the result list
result = []
 
# storing the product of keys and
# their respective values in result
for i, j in zip(k, v):
    result.append(i * j)
     
# displaying the result
print(result)
 
 

Output :

['a', 'h', 'i', 'l', 'n', 'oo', 'p', 'r', 'ttt', 'u', 'y']


Next Article
Python - Convert Dictionary Object into String

G

gauravbabbar25
Improve
Article Tags :
  • Python
  • python-dict
  • Python-dict-functions
Practice Tags :
  • python
  • python-dict

Similar Reads

  • Python | Words extraction from set of characters using dictionary
    Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It che
    3 min read
  • Python Dictionary to find mirror characters in a string
    Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end.
    2 min read
  • Replacing Characters in a String Using Dictionary in Python
    In Python, we can replace characters in a string dynamically based on a dictionary. Each key in the dictionary represents the character to be replaced, and its value specifies the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel
    2 min read
  • Convert a List of Characters into a String - Python
    Our task is to convert a list of characters into a single string. For example, if the input is ['H', 'e', 'l', 'l', 'o'], the output should be "Hello". Using join() We can convert a list of characters into a string using join() method, this method concatenates the list elements (which should be stri
    2 min read
  • Python - Convert Dictionary Object into String
    In Python, there are situations where we need to convert a dictionary into a string format. For example, given the dictionary {'a' : 1, 'b' : 2} the objective is to convert it into a string like "{'a' : 1, 'b' : 2}". Let's discuss different methods to achieve this: Using strThe simplest way to conve
    2 min read
  • How to print Odia Characters and Numbers using Python?
    Odia(ଓଡ଼ିଆ) is an Indo-Aryan language spoken in the Indian state of Odisha. The Odia Script is developed from the Kalinga alphabet, one of the many descendants of the Brahmi script of ancient India. The earliest known example of Odia language, in the Kalinga script, dates from
    2 min read
  • Print anagrams together in Python using List and Dictionary
    An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The task of grouping anagrams together in Python can be efficiently solved using lists and dictionaries. The key idea is to process each word by sorting its charac
    2 min read
  • Map function and Dictionary in Python to sum ASCII values
    We are given a sentence in the English language(which can also contain digits), and we need to compute and print the sum of ASCII values of the characters of each word in that sentence. Examples: Input : GeeksforGeeks, a computer science portal for geeksOutput : Sentence representation as sum of ASC
    2 min read
  • Python - Converting list string to dictionary
    Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-val
    3 min read
  • Find all duplicate characters in string in Python
    In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary. Using Loop with DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iterati
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences