Home > OS >  How to change dictionary format in python?
How to change dictionary format in python?

Time:12-02

I need to transform dict { name : department } to { department : [ name ] } and print all names after transformation, but it prints me only one, what is wrong here?

I need to use dictionary comprehension method.

Tried this, but it doesn't work as expected:

orig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': \
             'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}

new_dict = {value: [key] for key, value in orig_dict.items()}

it_names = new_dict['IT']

print(it_names)

CodePudding user response:

It appears that you want values to become keys in a new dictionary and the values to be a list. If so, then:

orig_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}
new_dict = {}
for k, v in orig_dict.items():
    new_dict.setdefault(v, []).append(k)
print(new_dict)

Output:

{'HR': ['Tom', 'Margo'], 'IT': ['Ted', 'Jesica'], 'Marketing': ['Ken', 'Jason']}

CodePudding user response:

Full Code

old_dict = {'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing',
            'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT', 'Margo': 'HR'}
# Printing original dictionary
print("Original dictionary is : ")
print(old_dict)

print()
new_dict = {}
for key, value in old_dict.items():
    if value in new_dict:
        new_dict[value].append(key)
    else:
        new_dict[value] = [key]

# Printing new dictionary after swapping
# keys and values
print("Dictionary after swapping is :  ")
print("keys: values")
for i in new_dict:
    print(i, " :", new_dict[i])

it_names = new_dict['IT'] 
print(it_names)

Output

Original dictionary is : 
{'Tom': 'HR', 'Ted': 'IT', 'Ken': 'Marketing', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'HR'}       

Dictionary after swapping is :
keys: values
HR  : ['Tom', 'Margo']
IT  : ['Ted', 'Jesica']
Marketing  : ['Ken', 'Jason']
['Ted', 'Jesica']
  • Related