Skip to content

Instantly share code, notes, and snippets.

@Justintime50
Created April 21, 2022 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Justintime50/80d94819da527c95e41e0be743e0f0c0 to your computer and use it in GitHub Desktop.
Save Justintime50/80d94819da527c95e41e0be743e0f0c0 to your computer and use it in GitHub Desktop.
Invert a dictionaries keys and values
import json
import os
# Invert a dictionary's keys and values
# USAGE: FILE=myfile.json venv/bin/python invert_dictionary.py
FILE = os.getenv('FILE')
def main():
with open(FILE, 'r') as dictfile:
data = dictfile.read()
json_data = json.loads(data)
new_dict = {}
for key, value in json_data.items():
new_dict.update({value: key})
print(json.dumps(new_dict, indent=4))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment