• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Swapping dict keys and values in Python

Posted Dec 18, 2022 — Updated Jan 10, 2024

Sometimes you need to invert the keys and values in a dictionary. Fortunately, Python gives us a concise way to do exactly that with list comprehensions and dict.items():


person = {
    "first_name": "Justin",
    "job": "engineer",
    "age": 100,
}

# Normally the word 'key' should be avoided, other languages like JS 
# have that word reserved. In practice I'd use 'k' and 'v' here
inverted = {value: key for key, value in person.items()}

print(inverted)
"""
{
    'Justin': 'first_name',
    'engineer': 'job',
    100: 'age'
}
"""

However, if you have nested dictionaries this method won’t work:

person = {
	"first_name": "Justin",
    "address": {
    	"street_1": "123 Main st",
        "city": "New York City",
    },
}

inverted = {v: k for k,v in person.items()}
// TypeError: unhashable type: 'dict'

This error is caused by attempting to use the entire "address" dict as a key in the new inverted dict. If you need to invert a dictionary which itself contains dictionaries or other unhashable types like lists, the code gets complicated quickly and will vary based on exactly what you’re trying to accomplish.


Helpful Links

  • The items() method – Python docs
  • Python list comprehensions – Me!

Filed Under: Python

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 · Contact me at justin [at] {this domain}

  • Privacy Policy