是否有可能使用字典理解来反转python中的字典 [英] is it possible to reverse a dictionary in python using dictionary comprehension

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

问题描述

我想使用字典理解来反转字典 key,value 对,但是如果新字典的某个键具有多个值,则将其替换为最后一个值.

I want to reverse dictionary key, value pairs using a dictionary comprehension, but if the new dictionary has more than one value for a key then it is getting replaced with the last value.

如果使用理解力重复键,是否可以在新字典中附加值?

Is it possible to append to the values in the new dictionary if a key is repeated, using a comprehension?

输入:

test_di = {'a':'1', 'b':'2', 'c':'3', 'd':'2'}

代码:

{v:k for k,v in test_di.items()} 

此代码的输出:

{'1': 'a', '3': 'c', '2': 'd'}

所需的输出:

{'1': ['a'], '3': ['c'], '2': ['b','d']}

推荐答案

不可能以合理的方式(即 O(N)时间)来进行字典理解.理解根本无法处理重复的值.

It's not possible to do it in a reasonable way (i.e. O(N) time) with a dictionary comprehension. The comprehension simply can't handle duplicated values.

但是,使用常规循环非常容易:

However, it's quite easy with a regular loop:

d = {}
for key, value in old_d.items():
    d.setdefault(value, []).append(key)

这篇关于是否有可能使用字典理解来反转python中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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