有没有一种方法可以获取指定位置的键?

huangapple go评论49阅读模式
英文:

Is there a way to get the key at a specified position?

问题

我想要在字典中的特定位置(比如1)打印出一个键,但代码似乎根本不起作用。

Hobbies={
  football(american):1
  baseball:2
  basketball:3
  playing_cards:4
  swimming:5
  soccer:7
}

我使用了这行代码:

print (Hobbies[1])

但出现了一个错误。我该如何修复它?

英文:

I wanted to print out a key at a specific position (like 1) in a dictionary, but the code didn't seem to work at all.

    Hobbies={
      football(american):1
      baseball:2
      basketball:3
      playing_cards:4
      swimming:5
      soccer:7
   }

I used this line :

     print (Hobbies[1])

But it got an error
How should I fix it?

答案1

得分: 0

首先,你可能不应该这样做,因为这不是字典的预期访问方式。

但是如果你真的需要这样做,可能最直接的方法是获取字典中的键列表,然后使用第一个键访问字典。

类似这样:

list_of_keys = [key for key in Hobbies.keys()]
key_of_interest = list_of_keys[0]
value_of_interest = Hobbies[key_of_interest]

或者可以写成一行:

value_of_interest = Hobbies[[key for key in Hobbies.keys()][0]]

这也可能起作用,但我不能确定值的顺序是否与键的顺序保证相同。可能是的,但我不能确定:

value_of_interest = [value for value in Hobbies.values()][0]
英文:

First off, you probably shouldn't do this, because this is not how dictionaries were intended to be accessed.

But if you really need to do this, probably the most straightforward way is to get the list of keys from the dictionary, and then access the dictionary using the first key.

Something like:

list_of_keys = [key for key in Hobbies.keys()]
key_of_interest = list_of_keys[0]
value_of_interest = Hobbies[key_of_interest]

Or as a one-liner:

value_of_interest = Hobbies[[key for key in Hobbies.keys()][0]]

This may also work, but I'm not sure if the order of values is guaranteed the same way the order of keys is. It probably is, but I can't say for sure:

value_of_interest = [value for value in Hobbies.values()][0]

huangapple
  • 本文由 发表于 2023年6月1日 23:40:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定