用于在具有多个相等值的字典中交换键/值的字典理解 [英] Dictionary comprehension for swapping keys/values in a dict with multiple equal values

查看:29
本文介绍了用于在具有多个相等值的字典中交换键/值的字典理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def invert_dict(d):
    inv = dict()
    for key in d:
        val = d[key]
        if val not in inv:
            inv[val] = [key]
        else:
            inv[val].append(key)
return inv

这是 Think Python 书中的一个示例,一个用于反转(交换)字典中的键和值的函数.新值(以前的键)被存储为列表,所以如果有多个字典值(绑定到不同的键)在反转之前相等,那么这个函数只是将它们附加到以前的键列表中.

This is an example from Think Python book, a function for inverting(swapping) keys and values in a dictionary. New values (former keys) are stored as lists, so if there was multiple dictionary values (bound to a different keys) that were equal before inverting, then this function simply appends them to the list of former keys.

示例:

somedict = {'one': 1, 'two': 2, 'doubletwo': 2, 'three': 3}
invert_dict(somedict) ---> {1: ['one'], 2: ['doubletwo', 'two'], 3: ['three']}

我的问题是,字典理解也可以这样做吗?这个函数创建一个空的 dict inv = dict(),然后在函数中用 if/else 检查它是否存在值.在这种情况下,字典理解应该自我检查.这可能吗?语法应该是什么样的?

My question is, can the same be done with dictionary comprehensions? This function creates an empty dict inv = dict(), which is then checked later in the function with if/else for the presence of values. Dict comprehension, in this case, should check itself. Is that possible, and how the syntax should look like?

交换值的一般字典理解语法是:

General dict comprehension syntax for swapping values is:

{value:key for key, value in somedict.items()}

但是如果我想添加一个如果"分句,它应该是什么样子的?如果值不在(什么)中?

but if I want to add an 'if' clausule, what it should look like? if value not in (what)?

谢谢.

推荐答案

你可以使用 set comprehension 副作用:

You can use a set comprehension side effect:

somedict = {'one': 1, 'two': 2, 'doubletwo': 2, 'three': 3}

invert_dict={}
{invert_dict.setdefault(v, []).append(k) for k, v in somedict.items()}

print invert_dict
# {1: ['one'], 2: ['doubletwo', 'two'], 3: ['three']}

这篇关于用于在具有多个相等值的字典中交换键/值的字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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