Apurba Adhikari
Apurba Adhikari

Reputation: 41

How to change key to value in python?

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"]}

Upvotes: 0

Views: 68

Answers (3)

milanbalazs
milanbalazs

Reputation: 5329

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']}

Upvotes: 0

Lambo
Lambo

Reputation: 1174

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

Upvotes: 0

Julien
Julien

Reputation: 15071

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

Upvotes: 1

Related Questions