问题描述
所以例如:
$ b $我想尝试使用现有dict的值列表创建一个新的dict。 b dict1 = dict({'a':[1,2,3],'b':[1,2,3,4],'c ':[1,2]})
我想获取:
dict2 = dict({1:['a','b','c'],2:['a','b' ,'c'],3:['a','b'],4:['b']})
到目前为止,我没有能够以非常干净的方式做到这一点。任何建议?
如果您使用的是Python 2.5或更高版本,请使用模块;一个 defaultdict
会自动创建第一次访问缺少的密钥的值,因此您可以使用此值创建 dict2
,像这样:
从集合import defaultdict
dict1 = dict({'a':[1, 2,3],'b':[1,2,3,4],'c':[1,2]})
dict2 = defaultdict(list)
用于键,dict1中的值.items():
值中的值:
#自动创建dict2 [value]的列表
dict2 [value] .append(key)
请注意,dict2中的列表不会是任何特定的顺序,因为字典不会对其键值对排序。
如果你想要一个普通的命令,最后会提出一个 KeyError
缺少的键,只需使用 dict2 = dict(dict2)
之后。
I am trying to create a new dict using a list of values of an existing dict as individual keys.
So for example:
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
and I would like to obtain:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
So far, I've not been able to do this in a very clean way. Any suggestions?
If you are using Python 2.5 or above, use the defaultdict
class from the collections
module; a defaultdict
automatically creates values on the first access to a missing key, so you can use that here to create the lists for dict2
, like this:
from collections import defaultdict
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
dict2 = defaultdict(list)
for key, values in dict1.items():
for value in values:
# The list for dict2[value] is created automatically
dict2[value].append(key)
Note that the lists in dict2 will not be in any particular order, as a dictionaries do not order their key-value pairs.
If you want an ordinary dict out at the end that will raise a KeyError
for missing keys, just use dict2 = dict(dict2)
after the above.
这篇关于Python中的反义词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!