How To Transform Dictionary In Python?

Last updated on December 2nd, 2022

Let’s say we have a dictionary dict1 where we have names (key) and job departments (value), but we want to get names sorted by departments aka we need to transform the dictionary format.

How-To-Transform-Dictionary-In-Python

To transform the dictionary from the format:

{'Ramunas': 'Marketing', 'Thomas': 'IT', 'Jacob': \
'HR', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT'} 

to the format:

This website is supported by readers like you. If you purchase after clicking one of our affiliate links, we may earn a small commission at no extra cost to you.

{'HR': ['Jacob'], 'IT': ['Thomas', 'Jesica', 'Margo'], 'Marketing': \['Ramunas', 'Jason']}

you can use a loop to iterate over the items in the original dictionary and add the keys and values to the new dictionary as necessary.

The second method would be list comprehension, though sometimes this may be not the best option.

Using Loop Method

Here are the steps you would need to follow to do this:

  1. Create an empty dictionary to store the transformed data. This will be the dictionary that you will return to at the end of the transformation.
  2. Loop over the items in the original dictionary. For each item, you will have the key (the name) and the value (the job department).
  3. If the value (the job department) is not already a key in the new dictionary, add it as a key with an empty list as the value (see also, ‘How to Sum Values in a Python List?‘). This will initialize the list for the job department so that you can add the names to it later.
  4. Append the key (the name) to the list for the corresponding value (the job department). This will add the name to the list of names for the job department.
  5. After the loop is finished, the new dictionary will contain the names sorted by job department. You can return this dictionary as the result of the transformation.

Here is the code you can take a look:

# the original dictionary
dict1 = {'Ramunas': 'Marketing', 'Thomas': 'IT', 'Jacob': 'HR',\
         'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT'}

# create an empty dictionary to store the transformed data
dict2 = {}

# loop over the items in the original dictionary
for key, value in dict1.items():
  # if the value is not already a key in the new dict, add it as a key
  # with an empty list as the value
  if value not in dict2:
    dict2[value] = []
  # append the key to the list for the corresponding value
  dict2[value].append(key)

  # the resulting dictionary will be of the form:
  # {department_name: [employee_name]}
print(dict2)

This process can be used to transform a dictionary from any format into any other format, as long as you know what data should be in the new dictionary. With a few simple steps, you can easily transform your dictionaries into Python (see also, ‘How to Split a List in Python?‘).

Using dictionary comprehension

Here are the steps you would need to follow to use dictionary comprehension to transform the dictionary in this case:

  1. Define the original dictionary dict1 as shown below.
  2. Create a dictionary comprehension to transform the data. This will be a single expression that specifies the key-value pairs you want to include in the new dictionary. In this case, you want the values from the original dictionary (the job departments) to be the keys in the new dictionary, and the keys from the original dictionary (the names) to be the values in the new dictionary. You can express this transformation using the following dictionary comprehension: {value: [key] for key, value in dict1.items()}
  3. Assign the result of the dictionary comprehension to a variable, such as dict2. This will create the new dictionary and store it in the dict2 variable.
  4. You can then use the dict2 variable to access the names sorted by job department. For example, to get the names for the IT department, you could use the following code: it_names = dict2['IT']. This would set the it_names variable to the list ['Thomas', 'Jesica', 'Margo'].

Here is the complete code that uses a dictionary comprehension to perform the transformation:

# transform dictionary using dict comprehension
# the original dictionary
dict1 = {'Ramunas': 'Marketing', 'Thomas': 'IT', 'Jacob': \
             'HR', 'Jason': 'Marketing', 'Jesica': 'IT', 'Margo': 'IT'}

# create a dictionary comprehension to transform the data
dict2 = {value: [key] for key, value in dict1.items()}

# access the names for the IT department
it_names = dict2['IT']

# print the names for the IT department
# this will print a list of all the names for the IT job department
print(it_names)

Using dictionary comprehension can make the code more concise and easy to read. However, it is not always the best option, depending on the complexity of the transformation you want to perform.

In this case, dictionary comprehension may be a good choice because the transformation is simple and can be easily expressed using a single expression. However, for more complex transformations, it may be easier to use a loop or other control flow constructs to perform the necessary operations.

Final words

You don’t need to be a Python expert to change dictionaries into other formats. As you can see from the example above, it’s quite easy and only takes a few lines of code. You just need to understand the desired output format and how to convert the data!

I’m still learning Python myself, so please let me know if you spot any errors in my code in the comments section below. Thanks for reading!

By Ramunas Berkmanas

As a full-stack marketer, I have been actively involved in the digital marketing industry since 2014. Over the years, I have gained extensive experience in various areas such as SEO, media buying, and performance marketing. Read my story

Leave a comment

Your email address will not be published. Required fields are marked *