如何访问字典的特定元素

时间:2018-01-26 14:06:37

标签: python python-2.7 dictionary scikit-learn

假设这是我的字典

test = {1:'a',2:'b',3:'c',4:'d',5:'e'}

如何使用for循环打印前三个元素?

2 个答案:

答案 0 :(得分:1)

此解决方案假设“前3个元素”表示“按键排序的前3个元素”。

<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <button @click="reply">
    Reply
  </button>
  <button @click="editComment">
    Edit
  </button>
  <comment-form v-if="showEditForm" key="edit" @close-form="closeForm" inline-template>
    <div>
      This is the edit form
      <button @click="close">
        Close it
      </button>
    </div>
  </comment-form>
  <comment-form id="reply" key="reply" v-if="showReplyForm" @close-form="closeForm" inline-template>
    <div>
      This is the reply form
      <button @click="close">
        Close it
      </button>
    </div>
  </comment-form>
</div>

注意:这可以在dictionaries are naturally ordered以后的python 3.6+中使用。为了获得更好的性能,请使用堆队列,而不是对所有键进行排序,然后列出切片。

答案 1 :(得分:1)

在Python中,字典本质上是无序的,以便按照您的意愿创建一个Ordered字典,该字典会记住键值对的插入顺序。以下是一些示例代码,可以执行您希望的操作

import collections
test = {1:'a',2:'b',3:'c',4:'d',5:'e'}
blah = collections.OrderedDict(test)
for x in range(3):
    print(blah.items()[x])

如果这是python 3,则必须将blah.items()调用包装在列表中,因为它返回一个可迭代的对象视图。以下是更多信息Accessing Items In a ordereddict

的链接
相关问题