Python dict switch keys and values

How to switch dictionary keys and values in python ?

Example of how to switch dictionary keys and values in python:

Switching dictionary keys and values

Let’s consider the following dictionary:

To iterate over all keys and values we can use items():

for x, y in d.items(): print(x,y) 

Then to create a new dictionary with inverted keys and values a straigtforward solution is to do:

Nested dictionaries

Another example: the goal is to switch keys and values of dictionaries inside another dictionary:

To iterate over all keys and values

for x, y in d.items(): print(x,y) for xn, yn in y.items(): print(xn,yn) 
table 1 A 1 B 2 C 3 table 2 D 4 E 5 F 6 

Example of use with a pandas dataframe

import pandas as pd df = pd.DataFrame(data=['A','B','C']) print(df) 
 0 0 A 1 B 2 C d = df.replace(d,inplace=True) print(df) 
 0 0 100 1 200 2 300 new_d = df.replace(new_d,inplace=True) print(df) 

See also

Links Tags
How to slice a dictionary (e.g create a sub-dictionary or sample) in python ? Python; Dictionary
How to shuffle randomly dictionary keys in python 3 ? Python; Dictionary
How to select randomly keys from a dictionary in python 3 ? Python; Dictionary
How to get the number of keys in a dictionary in python ? Python; Dictionary
How to iterate over a dictionary (keys and values) in python using a for loop ? Python; Dictionary
How to remove a key in a dictionary in python ? Python; Dictionary
How to iterate only over the first n elements of a very large dictionary in python ? Python; Dictionary
How to sort dictionary keys by alphabetical order (create an ordered dictionary) in python ? Python; Dictionary
How to find all keys in a dictionary with a given value in python ? Python; Dictionary
How to check if two dictionaries are the same in python ? Python; Dictionary
How to convert a dataframe to a dictionary with pandas in python ? Python; Dictionary
How to check if a dictionary has a given key in python 3 ? Python; Dictionary
How to save a dictionary in a json file with python ? Python; Dictionary
How to copy a dictionary in python ? Python; Dictionary

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

Skills

Источник

Python dict switch keys and values

Last updated: Mar 24, 2023
Reading time · 5 min

banner

# Table of Contents

# Swap the keys and values in a Dictionary in Python

To swap the keys and values in a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a dict comprehension to iterate over the view.
  3. Swap each key and value and return the result.
Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > new_dict = value: key for key, value in my_dict.items() > # 👇️ print(new_dict)

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > # 👇️ dict_items([('bobby', 'first'), ('hadz', 'last'), ('python', 'topic')]) print(my_dict.items())

We used a dict comprehension to iterate over the view object.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we swap the key and the value and return the result.

Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > new_dict = value: key for key, value in my_dict.items() > # 👇️ print(new_dict)

# Swap the keys and values in a Dictionary and handle Duplicate Values

The keys in a dictionary are unique so trying to add the same key to a dictionary multiple times simply overrides the value of the key.

If you try to swap the keys and values of a dictionary that contains duplicate values, you'd lose some of the key-value pairs.

One way to get around this is to store the values in the new dictionary using a list.

Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', 'django': 'topic', 'flask': 'topic', > new_dict = > for key, value in my_dict.items(): if value in new_dict: new_dict[value].append(key) else: new_dict[value] = [key] # # 'last': ['hadz'], # 'topic': ['python', 'django', 'flask']> print(new_dict)

The original dictionary has multiple values equal to the string topic .

  1. We iterate over the dictionary's items.
  2. On each iteration, we check if the current value is contained in the keys of the new dictionary.
  3. If the condition is met, we append the current key to the list of values in the new dictionary.
  4. Otherwise, we initialize a new key-value pair.

You can also use the dict() class.

# Swap the keys and values in a Dictionary using dict()

This is a three-step process:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a generator expression to iterate over the view object.
  3. Swap each key and value in the call to the dict() class.
Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > new_dict = dict( (value, key) for key, value in my_dict.items() ) # 👇️ print(new_dict)

We used the dict.items() method to get a view of the dictionary's items and used a generator expression to iterate over the view object.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we return a tuple containing the value and key.

The dict() class can be passed an iterable of key-value pairs and returns a new dictionary.

Alternatively, you can use a simple for loop.

# Swap the keys and values in a Dictionary using a for loop

This is a three-step process:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a for loop to iterate over the view object.
  3. Swap each key and value and add them to a new dictionary.
Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > new_dict = > for key, value in my_dict.items(): new_dict[value] = key # 👇️ print(new_dict)

We declared a new variable that stores an empty dictionary.

We used a for loop to iterate over the items of the original dictionary.

On each iteration, we swap each key and value and assign the pair to the new dictionary.

Alternatively, you can use the zip() function.

# Swap the keys and values in a Dictionary using zip()

This is a three-step process:

  1. Use the dict.keys() and dict.values() methods to get a view of the dictionary's keys and values.
  2. Use the zip() function to produce a tuple with each value and key.
  3. Pass the tuples to the dict() class.
Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > new_dict = dict( zip(my_dict.values(), my_dict.keys()) ) # 👇️ print(new_dict)

The dict.values method returns a new view of the dictionary's values.

Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > # 👇️ dict_values(['first', 'last', 'topic']) print(my_dict.values()) # 👇️ dict_keys(['bobby', 'hadz', 'python']) print(my_dict.keys())

The dict.keys method returns a new view of the dictionary's keys.

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

The zip function returns an iterator of tuples.

Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > # 👇️ [('first', 'bobby'), ('last', 'hadz'), ('topic', 'python')] print(list(zip( my_dict.values(), my_dict.keys() )))

The last step is to pass the iterator of tuples to the dict() class.

Copied!
my_dict = 'bobby': 'first', 'hadz': 'last', 'python': 'topic', > new_dict = dict( zip(my_dict.values(), my_dict.keys()) ) # 👇️ print(new_dict)

Which approach you pick is a matter of personal preference. I'd use a dict comprehension as I find them quite direct and easy to read.

Want to learn more about working with dictionaries in Python ? Check out these resources: Check if all values in a Dictionary are equal in Python ,How to Replace values in a Dictionary in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Swap dictionary keys and values in Python

This article explains how to swap keys and values in a dictionary ( dict ) in Python.

Swap keys and values with dictionary comprehension and items()

You can swap keys and values in a dictionary with dictionary comprehensions and the items() method.

d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> d_swap = v: k for k, v in d.items()> print(d_swap) # 
def get_swap_dict(d): return v: k for k, v in d.items()> d_swap = get_swap_dict(d) print(d_swap) # 

Note on dictionaries with duplicate values

In a dictionary, all keys must be unique, but values can be duplicated.

When swapping keys and values in a dictionary that contains duplicate values, only one instance of the duplicate value will be retained, since dictionary keys must be unique.

d_duplicate = 'key1': 'val1', 'key2': 'val1', 'key3': 'val3'> d_duplicate_swap = get_swap_dict(d_duplicate) print(d_duplicate_swap) # 

Источник

Читайте также:  Filter application in java
Оцените статью