首页 > 解决方案 > 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?

标签: pythondictionary

解决方案


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]]

推荐阅读