将Python字典键分组为列表,并创建一个具有此列表的新字典作为值 [英] Grouping Python dictionary keys as a list and create a new dictionary with this list as a value

查看:808
本文介绍了将Python字典键分组为列表,并创建一个具有此列表的新字典作为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python字典

  d = {1:6,2:1,3:1,4:9 ,5:9,6:1} 

由于上述字典中的值不是唯一的。我想将唯一值的所有键分组为列表,并创建一个新的字典如下:

  v = {6 :[1],1:[2,3,6],9:[4,5]} 



<注意,新字典 v 的键应该被排序。我很难看出并实现这个字典的创作。请给我一个简单而有效的方法。

解决方案

使用 collections.defaultdict 放心:

 从集合导入defaultdict 

v = defaultdict(list)

为键,值在排序(d.iteritems() ):
v [value] .append(key)

但是你可以用bog-standard dict 也是:​​

  v = {} 

为键,值在排序(d.iteritems())中:
v.setdefault(value,[])。append(key)
pre>

在Python 3中,使用 sorted(d.items())


I have a python dictionary

d = {1: 6, 2: 1, 3: 1, 4: 9, 5: 9, 6: 1}

Since the values in the above dictionary are not unique. I want to group the all the keys of unique values as a list and create a new dictionary as follows:

v = {6:[1], 1:[2, 3, 6], 9: [4, 5]}

Note the keys of new dictionary v should be sorted. I am finding it hard to visualize and implement this dictionary creation. Please suggest me an easy and efficient way to do it.

解决方案

Using collections.defaultdict for ease:

from collections import defaultdict

v = defaultdict(list)

for key, value in sorted(d.iteritems()):
    v[value].append(key)

but you can do it with a bog-standard dict too:

v = {}

for key, value in sorted(d.iteritems()):
    v.setdefault(value, []).append(key)

In Python 3, use sorted(d.items()) instead.

这篇关于将Python字典键分组为列表,并创建一个具有此列表的新字典作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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