python反向字典 [英] python reverse dictionary

查看:167
本文介绍了python反向字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供了字典:

 d = {'name': 'Luke', 'age': 43, 'friend': 'Joe'}

我正在尝试构建一个函数来对其进行更改,以便新词典将是:

i'm trying to build a function that will change it so that the new dictionary will be:

d = {'Luke': 'name', 43: 'age', 'Joe':'friend'}

换句话说,键将成为值,而值将成为键. 字典的ID也不会改变.

in other words the key will become the values and the values will become the keys. also the id of the dictionary wont change.

我尝试了以下代码:

dict(map(reversed, d.items()))

我正在使用python 3.x 任何帮助将不胜感激.

i'm using python 3.x any help will be appreciated.

推荐答案

如果要在不更改其ID的情况下反转字典,则需要构建一个临时字典,清除旧字典并进行更新.这是使用字典理解的方法.

If you want to invert the dictionary without changing its id you need to build a temporary dictionary, clear the old one, and update it. Here's how to do that using a dictionary comprehension.

d = {'name': 'Luke', 'age': 43, 'friend': 'Joe'}
print(d, id(d))

# Invert d
t = {v: k for k, v in d.items()}

# Copy t to d
d.clear()
d.update(t)
# Remove t
del t
print(d, id(d))

输出

{'name': 'Luke', 'age': 43, 'friend': 'Joe'} 3072452564
{'Luke': 'name', 43: 'age', 'Joe': 'friend'} 3072452564

使用Python 3.6进行了测试,它保留了普通字典的顺序. 严格来说,del t不是必需的,但是如果不需要它也可以.当然,如果您在函数t中进行此操作,则无论如何只要超出范围,它就会立即收集垃圾.

Tested using Python 3.6, which preserves the order of plain dictionaries. It's not strictly necessary to del t, but you might as well if you don't need it. Of course, if you're doing this inside a function t will get garbage collected as soon as it goes out of scope anyway.

执行此操作时需要小心:所有值都必须是不可变的对象,任何重复的值都会被破坏.

You need to be careful when doing this: all the values must be immutable objects, and any duplicated values will get clobbered.

虽然这是完全合法的,但有些人认为为字典键混合类型是不好的样式.而且,如果您要创建字典项的排序列表,并且键为混合类型,则在Python 3中将无法轻松实现.您无法对混合类型的键进行排序,因为Python 3不允许您比较混合类型的对象.

Also, while it's perfectly legal, some people consider it bad style to have mixed types for your dictionary keys. And if you want to create a sorted list of the dict's items you won't be able to do that easily in Python 3 if the keys are of mixed types. You can't sort keys of mixed types because Python 3 doesn't permit you to compare objects of mixed type.

这篇关于python反向字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆