Open In App

Python – Append Similar Values as Key

Last Updated : 01 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we can have problems in which we need to categorize a particular list and values to similar keys. This can be a problem in counting data. Like counting votes or counting coins. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using loop This is the brute way in which this task can be performed. In this, we run a loop to add values to the dictionary value list, if not present we dynamically create a key and perform append. 

Python3




# Python3 code to demonstrate working of
# Append Similar Values as Key
# Using loop
 
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
             'Manjeet', 'Akash', 'Akshat', 'Manjeet']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Append Similar Values as Key
# Using loop
res = dict()
for ele in test_list:
    try:
        res[ele].append(ele)
    except KeyError:
        res[ele] = [ele]
 
# printing result
print("The similar values dictionary is : " + str(res))


Output

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Nikhil': ['Nikhil'], 'Akshat': ['Akshat', 'Akshat'], 'Akash': ['Akash', 'Akash']}

Time Complexity: O(n), where n is the number of elements in the list. The time complexity is linear because the loop iterates through each element in the list and checks if it exists in the dictionary. If it does, it appends the element, and if it doesn’t, it creates a new key-value pair.
Auxiliary Space: O(n), where n is the number of elements in the list. The auxiliary space is linear because the dictionary stores each unique element in the list as a key, with a value of a list containing the duplicates.

Method #2: Using defaultdict() + loop The combination of the above functions can be used to solve this problem. In this, pre-initializeize the dictionary using defaultdict(). 

Python3




# Python3 code to demonstrate working of
# Append Similar Values as Key
# Using defaultdict() + loop
from collections import defaultdict
 
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
             'Manjeet', 'Akash', 'Akshat', 'Manjeet']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Append Similar Values as Key
# Using defaultdict() + loop
res = defaultdict(list)
for sub in test_list:
    res[sub].append(sub)
 
# printing result
print("The similar values dictionary is : " + str(dict(res)))


Output

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Nikhil': ['Nikhil'], 'Akshat': ['Akshat', 'Akshat'], 'Akash': ['Akash', 'Akash']}

Time complexity: O(n), where n is the number of elements in the test_list.
Auxiliary space: O(n), where n is the number of elements in the test_list. 

Method #3 : Using list(),set(),count() methods

Python3




# Python3 code to demonstrate working of
# Append Similar Values as Key
# Using loop
 
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
                        'Manjeet', 'Akash', 'Akshat', 'Manjeet']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Append Similar Values as Key
# Using loop
res = dict()
x = list(set(test_list))
for i in x:
    res[i] = [i]*test_list.count(i)
# printing result
print("The similar values dictionary is : " + str(res))


Output

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Nikhil': ['Nikhil'], 'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Akash': ['Akash', 'Akash'], 'Akshat': ['Akshat', 'Akshat']}

Time Complexity: O(n^2), where n is the length of the input list
Auxiliary Space: O(n), as we are using a dictionary to store the result, which can have up to n key-value pairs in the worst case.

Method #4 : Using get():

Python3




# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
# printing original list
print("The original list is : " + str(test_list))
# Using a dictionary and the get() method
result = {}
for sub in test_list:
    result[sub] = result.get(sub, []) + [sub]
# printing result
print("The similar values dictionary is : " + str(result))
#This is code is contributed by Jyothi Pinjala


Output

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Nikhil': ['Nikhil'], 'Akshat': ['Akshat', 'Akshat'], 'Akash': ['Akash', 'Akash']}

Time complexity: O(n)
Auxiliary Space: O(1)

Method #5: Using defaultdict() + list comprehension

Use a defaultdict(list) to create a dictionary where each key is initialized to an empty list. Then iterate over each item in the test_list and append it to the corresponding key in the dictionary. Finally, convert the defaultdict back to a regular dictionary using a dictionary comprehension.

Python3




from collections import defaultdict
 
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Append Similar Values as Key
# Using defaultdict() + list comprehension
res = defaultdict(list)
for item in test_list:
    res[item].append(item)
res = {key: value for key, value in res.items()}
 
# printing result
print("The similar values dictionary is : " + str(res))


Output

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Nikhil': ['Nikhil'], 'Akshat': ['Akshat', 'Akshat'], 'Akash': ['Akash', 'Akash']}

Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(n), where n is the length of the test_list. This is because we need to create a dictionary that has a key for each unique value in the test_list, which requires additional memory.

Method #6: Using setdefault() method

Follow the below steps to implement the above idea:

  • Initialize an empty dictionary “res“.
  • Loop through each element “ele” in the “test_list“.
  • Use the “setdefault()” method to insert a key-value pair into the dictionary “res“, where the key is the current element “ele“, and the value is an empty list “[]”.
  • Append the current element “ele” to the list value associated with the key “ele” in the “res” dictionary.
  • Return the “res” dictionary containing similar values as keys.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Append Similar Values as Key
# Using setdefault()
 
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
             'Manjeet', 'Akash', 'Akshat', 'Manjeet']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Append Similar Values as Key
# Using setdefault()
res = {}
for ele in test_list:
    res.setdefault(ele, []).append(ele)
 
# printing result
print("The similar values dictionary is : " + str(res))


Output

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Nikhil': ['Nikhil'], 'Akshat': ['Akshat', 'Akshat'], 'Akash': ['Akash', 'Akash']}

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #7: Using groupby from itertools

In this method, we groups the elements in the list based on their values. In this case, we first sort the list using sorted(). Then, we iterate over the groups of elements with the same value and add them to the dictionary with the key being the value of the group.

Python3




from itertools import groupby
 
# initializing list
test_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',
             'Manjeet', 'Akash', 'Akshat', 'Manjeet']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Append Similar Values as Key
# Using groupby()
res = {}
for key, group in groupby(sorted(test_list)):
    res[key] = list(group)
 
# printing result
print("The similar values dictionary is : " + str(res))


Output:

The original list is : ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet']
The similar values dictionary is : {'Manjeet': ['Manjeet', 'Manjeet', 'Manjeet'], 'Nikhil': ['Nikhil'], 'Akshat': ['Akshat', 'Akshat'], 'Akash': ['Akash', 'Akash']}

Time Complexity: O(nlogn), due to the initial sorting operation
Auxiliary Space: O(n), for the dictionary created in the end.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads