简体   繁体   中英

Print a specific key (e.g., third key) from a Python dictionary

I'm not sure why I am struggling to find this answer, but I am. I want to print the third key and item from a Python dictionary. I don't want to for loop and print all values like many other questions seem to ask. Simply, I just want dictionaryData.keys()[2] . I know this is incorrect, but this is what I am trying to accomplish.

What is the correct way to obtain the third key from a dictionary?

To print the third key and its associated value you could do this:

d = {1:'A',2:'B',3:'C'}

print(*list(d.items())[2])

Output:

3 C

Note:

This assumes that there at least 3 key/value pairs in the dictionary

Or:

If you just want to be weird then:

_, _, (k, v), *_ = d.items()
print(k, v)

i think Carl HR's answer is the easiest and straight forward way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM