将python中的字典反转为key:值列表? [英] Reverse a dictionary in python to key : list of values?

查看:179
本文介绍了将python中的字典反转为key:值列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将python字典d = {1:10, 2:20, 3:30, 4:30}转换为{10: [1], 20: [2], 30: [3, 4]}?

How to convert a python dictionary d = {1:10, 2:20, 3:30, 4:30} to {10: [1], 20: [2], 30: [3, 4]}?

我需要反转字典,其值应成为另一本字典的键,并且值应是列表中的键,即排序后的内容中的键.

I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter.

推荐答案

d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
    inv[val] = inv.get(val, []) + [key]

尝试一下!

这篇关于将python中的字典反转为key:值列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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