python - 如何打印字典中选定的项目?

标签 python

我知道这是非常基本的,但这是我的代码:

dict = {'blue':475, 'Green':530, 'Red':650, 'IR':800, 'UV':300}
x = dict['IR'] + dict['UV']
x //= 2
dict['Visible'] = x
print('IR',dict['IR'], 'UV',dict['UV'], 'Visible',dict['Visible'])

我只想打印字典中的最后 3 个(不是红色,但可见)项目。虽然它有效,但我认为必须有一种更直接的方法。

谢谢

最佳答案

Python 中的字典排序很困惑,并且在整个 Python 版本中实现的细节已经改变了很多次。

从 Python 3.7 开始,the dict docs保证 dict 的迭代顺序与插入顺序匹配。在 3.6 中,CPython 实现也是如此。相关引用:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

在 Python 3.5 及更早版本中,根本无法保证顺序(有时故意不确定,以防止人们依赖它!)。

因此,如果您想在 Python 3.7(或 CPython 3.6 实现)中打印最近插入的 3 个元素,您可以这样做:

my_dict = { . . . }
# Append some more stuff to my_dict

dict_in_insertion_order = list(my_dict.items())
# a list of key-value tuples, like [('IR', 800), ('UV', 300), ('Visible', 550)]
last_3 = dict_in_insertion_order[-3:]

这使用了 Python 的列表切片,其中起始索引 -3 表示“从末尾算起 3”。

编辑添加:

当然,如果您不关心一般情况的解决方案,您始终可以只指定要打印的键,如下所示:

for key in ['IR', 'UV', 'Visible']:
    print(key + ':', my_dict[key])  # Prints: IR: 800, then UV: 300, etc.

关于python - 如何打印字典中选定的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53676030/

相关文章:

python - 值错误 : could not convert string to float in dictionary

python - PyInstaller 找不到 PyYAML 隐藏导入

python - 从python中的子序列中获取所有可能的字符串

python - Pandas 在列中找到最接近的值

python - FastCGI 在 stderr : "Primary script unknown" - nginx and silex 中发送

python - "OSError: [Errno 2] No such file or directory"使用带有命令和参数的 python 子进程

python - 检查包含的内存有效方法

python - 无法在 Pycharm 的 python 控制台上导入模型

python - 通过iPython和伪控制台运行doctest

python - 使用 swig 继承 c++ 时出错