如何在python中打印字典,如果值与字典中的另一个值匹配,它们是否打印在同一行上?
代码:
result = {'light':4,'plane':4, 'vehicle':5}
print(result)
当前输出:
{'light': 4, 'plane': 4, 'vehicle': 5}
预期产出:
4 light, plane
5 vehicle
您如何计算预期输出中的单词频率?例如,光+平面是2。 谢谢。
答案 0 :(得分:1)
您可以尝试这样:
from collections import defaultdict
v = defaultdict(list)
d = {'light':4,'plane':4, 'vehicle':5}
for key, value in sorted(d.items()):
v[value].append(key)
这也有效:
k = {}
for key, value in sorted(d.items()):
k.setdefault(value, []).append(key)
更新: 如果您想以所需的格式打印它:
for i, j in v.items():
print(i,", ".join(l for l in j))
O / P将如下:
4 light, plane
5 vehicle
更新2: 以上述所需格式打印的代码如下:
from collections import defaultdict
v = defaultdict(list)
d = {'light':4,'plane':4, 'vehicle':5}
for key, value in sorted(d.items()):
v[value].append(key)
for i, j in v.items():
print(i,", ".join(l for l in j))