反转字典并显示值

时间:2016-03-13 15:12:19

标签: python dictionary

我想要反转字典并以特定格式显示它。以下是示例输入:

#include <opencv2/opencv.hpp>
#include <opencv2/cudaarithm.hpp>

int main()
{
    cv::Mat img = cv::imread("img.jpg", cv::IMREAD_GRAYSCALE);
    cv::Mat img_32f;
    img.convertTo(img_32f, CV_32F);
    //To avoid log(0) that is undefined
    img_32f += 1.0f;

    cv::cuda::GpuMat gpuImg, gpuImgLog;
    gpuImg.upload(img_32f);
    cv::cuda::log(gpuImg, gpuImgLog);

    cv::Mat imgLog, imgLog_32f;
    gpuImgLog.download(imgLog_32f);

    double min, max;
    cv::minMaxLoc(imgLog_32f, &min, &max);
    imgLog_32f.convertTo(imgLog, CV_8U, 255.0/(max-min), -255.0*min/(max-min));

    cv::imshow("img", img);
    cv::imshow("imgLog", imgLog);
    cv::waitKey(0);

    return 0;
}

输出应为:

enter image description here

这是我使用代码的地方,但问题是它返回一个列表而不是字典。

CODE:

{'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900} 

4 个答案:

答案 0 :(得分:4)

如果您想以这样的顺序打印您的项目,您不需要另一个字典,您可以循环遍历已排序的项目并打印键和值:

>>> d = {'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900}
>>> for k, v in sorted(d.items(), key = itemgetter(1), reverse=True):
...     print k, '\t', v
... 
alex    90.55
eva     88.5
tim     65.9
john    34.48
>>> 

但是如果你想以降序保存这些项目,由于字典不是像列表这样的有序数据结构,你可以使用collections.OrderedDict来创建有序字典:

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>>
>>> D = OrderedDict(sorted(d.items(), key = itemgetter(1), reverse=True))
>>> 
>>> D
OrderedDict([('alex', 90.55), ('eva', 88.5), ('tim', 65.9), ('john', 34.48)])

答案 1 :(得分:2)

  

我想按降序排列值

标准字典具有任意顺序。对字典进行排序的唯一方法是对(键,值)对进行排序并从中构建OrderedDict

>>> from collections import OrderedDict
>>> d = {'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900} 
>>> od = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
>>> od
OrderedDict([('alex', 90.55), ('eva', 88.5), ('tim', 65.9), ('john', 34.48)])
>>> od['eva']
88.5

印刷:

>>> for name, value in od.items():
...     print name, value
... 
alex 90.55
eva 88.5
tim 65.9
john 34.48

答案 2 :(得分:0)

import operator

x = {'john': 34.480, 'eva': 88.5, 'alex': 90.55, 'tim': 65.900}
res = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
print res

>>> [('alex', 90.55), ('eva', 88.5), ('tim', 65.9), ('john', 34.48)]

这就是你要找的东西。 你可以把它放到OrderedDict()

答案 3 :(得分:0)

简单代码,无需导入任何模块或库:

def formatted_print(D):
    list_tuples=sorted(D.items(), key=lambda x: (-x[1], x[0]))

    for items in list_tuples:
        x="{0:10s}{1:6.2f}".format(items[0],items[1])
        print(x)

打印:

alex       90.55
eva        88.50
tim        65.90
john       34.48