为给定字典的值返回具有键的字典,反之亦然 [英] Return a dictionary with keys for a given dictionary's values and vice versa

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

问题描述

在一个函数中,我如何创建一个字典谁的键是一个给定的字典的值,反之亦然,给定的字典每个键有多个值?
例如,给定一个字典:

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

我需要返回一个字典,如:

  d2 = { 一:[ 1, 2]中, b:[ 1, 2], C:[ 2, 3], D:[ 3 ]} 

我唯一的想法是列出所有值,然后手动检查每个键的每个键值,但是我不知道如何做到这一点,而不知道键和值的数量。任何帮助将非常感谢。

解决方案

尝试:

  {letter:[d键中的键,d [键]中的字母])(d [键]中的字母中的键的字母)} 

说明: set(d [key]中d为字母的字母)是一组出现在原始dict中的所有字母。然后我们创建一个新的字母,其中每个条目都是 letter:[在d [key]]中键入d的键),这意味着其中一个字母,映射到原始dict中映射到它的数字列表。


How would I, in a function, create a dictionary who's keys are a given dictionary's values, and vice versa, where the given dictionary has multiple values per key? For example, given a dictionary:

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

I'd need to return a dictionary like:

d2 = {"a":["1","2"],"b":["1","2"],"c":["2","3"],"d":["3"]}

My only idea was to make a list of all values, then manually check each key for each value, but I couldn't figure out how to do that without knowing the number of keys and values. Any help would be vastly appreciated.

解决方案

Try:

{letter: [key for key in d if letter in d[key]] for letter in set(letter for key in d for letter in d[key])}

Explanation: set(letter for key in d for letter in d[key]) is a set of all letters that appears in the original dict. Then we make a new dict, in which every entry is letter: [key for key in d if letter in d[key]], which means one of the letters, mapping to a list of numbers that mapped to it in the original dict.

这篇关于为给定字典的值返回具有键的字典,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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