python - How to select keys from a dictionary by their order?
问题描述
Sorry this is probably very simple, but I suspect I'm wording the question wrong from inexperience so I haven't been able to find the answer anywhere.
I have a dictionary, e.g.:
dict = {1: 'a', 2: 'b'}
I want to select specific values within the dictionary from knowing only their position in the dictionary.
For example I want to print the first key, and all I know about the key is that it's the first key in the dictionary, not its actual name to call on.
I am trying:
dict[0][0]
And I'm expecting this to output 1
, the first key in the dictionary - but I'm not experienced in python so I'm not sure how to get this working?
解决方案
This is probably what you were looking for.
Note this is for Python 3.7 and forward.
d = {1: 'a', 2: 'b'} # dict is a bad variable name! don't do it! it overrides a built-in!
d_keys = list(d.keys())
first_value = d[d_keys[0]]
推荐阅读
- pip - Dungeon Generator 不是通过 pip 安装的。python中的另一个C++ Build tools错误
- sql - Postgres 索引散列的大表
- varnish - 为什么在使用 libvmod-dynamic 时 varnishstat 中的计数器 MAIN.backend_unhealthy 不起作用?
- javascript - 这个函数的运行时复杂度是多少?
- javascript - react-ga 未将 Google Analytics Tracker 添加到页面
- python - 使用 pip 安装 web3 时出错。找不到满足 ipfshttpclient==0.7.0 要求的版本
- c# - 使用参数调用 resx 文本
- azure - 使用 Microsoft.Azure.Functions.Worker.Http 中的 HttpRequestData,如何检索远程 IP 地址?
- filtering - IIR 滤波的 SIMD 优化
- ssl - ActiveMQ Artemis ha=true 和 SSL 连接器