0
def allicate(a_dict):
    ans_dict = {}
    for key,item in a_dict.items():
        ans_dict[item] = [key]
    return ans_dict


my_dict = {
"name.txt":"Ram",
"teach.txt":"Shyam",
"cod.txt":"Ram"}

print(allicate(my_dict))

It should print

{"Ram":["name.txt","cod.txt"],
 "Shyam":["teach.txt"]}
Chris
  • 29,127
  • 3
  • 28
  • 51
  • 1
    Does this answer your question? [How do I exchange keys with values in a dictionary?](https://stackoverflow.com/questions/1031851/how-do-i-exchange-keys-with-values-in-a-dictionary) – furkanayd Mar 02 '20 at 05:43

3 Answers3

1

Try this:

from collections import defaultdict

def allicate(a_dict):
    ans_dict = defaultdict(list)
    for key,item in a_dict.items():
        ans_dict[item].append(key)
    return ans_dict
Julien
  • 13,986
  • 5
  • 29
  • 53
0
def allicate(a_dict):
    ans_dict = {}
    for key, value in a_dict.items():
        if value in ans_dict:
            ans_dict[value].append(key)
        else:
            ans_dict.update({value:[key]})
    return ans_dict

Lambo
  • 1,094
  • 11
  • 18
0

I have modified your code. You should check if your dict contains the required key or not (I have added comments to the related parts in the code. Please see below).

Code:

def allicate(a_dict):
    ans_dict = {}
    for key, item in a_dict.items():
        if item in ans_dict:  # If key exists in your dict.
            ans_dict[item].append(key)  # Append the element to the list.
            continue  # Get next element.
        ans_dict[item] = [key]  # Create a new key if it doesn't exist in you dict.
    return ans_dict


my_dict = {"name.txt": "Ram", "teach.txt": "Shyam", "cod.txt": "Ram"}

print(allicate(my_dict))

Output:

>>> python3 test.py
{'Ram': ['name.txt', 'cod.txt'], 'Shyam': ['teach.txt']}
milanbalazs
  • 4,811
  • 4
  • 23
  • 45