从字典中一行打印具有相同值的不同键 [英] Printing different keys that have same value in one row from a dictionary

查看:72
本文介绍了从字典中一行打印具有相同值的不同键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是示例字典.

example = {'a': 10, 'b': 12, 'c': 10, 'd': 12}

我想像下面那样打印它们.

I want to print them like below.

12 b, d
10 a, c

推荐答案

有两种方法可以解决此问题.

There are two ways you can approach this problem.

有效:collections.defaultdict(list)

用倒置的键和值构造一个新字典.重要的是,您可以有重复的值,因此我们使用列表来保存这些值. Pythonic方法是使用collections.defaultdict.

Construct a new dictionary with keys and values inverted. Importantly, you can have duplicate values, so we use a list to hold these. The Pythonic approach is to use collections.defaultdict.

对于非常大的词典,这可能会有很大的内存开销.

For very large dictionaries, this may have a large memory overhead.

example = {'a': 10, 'b': 12, 'c': 10, 'd': 12}

from collections import defaultdict

d = defaultdict(list)

for k, v in example.items():
    d[v].append(k)

for k, v in d.items():
    print(k, ' '.join(v))

10 a c
12 b d

手册:列表理解循环

这种方法在计算上效率低下,但是需要较少的内存开销:

This way is computationally inefficient, but requires less memory overhead:

for value in set(example.values()):
    print(value, ' '.join([k for k, v in example.items() if v == value]))

10 a c
12 b d

这篇关于从字典中一行打印具有相同值的不同键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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