简体   繁体   English

如何返回字典的前 4 个键?

[英]How to return the first 4 keys of a dictionary?

I'm trying to return a sentence where the number of words in the sentence is specified by the integer parameter, size.我正在尝试返回一个句子,其中句子中的单词数由整数参数 size 指定。 I tried to loop through the keys using我尝试使用

for key in word_positions_dict.keys()

and then got stuck after that.然后在那之后卡住了。

For example:例如:

my_dict = {'all': [0], 'animals': [1, 6], 'are': [2, 7], 'equal': [3, 9], 'but': [4], 'some': [5], 'more': [8], 'than': [10], 'others': [11]}
print(build_sentence(my_dict, 4))

output should be = all animals are equal输出应该是=所有动物都是平等的

To create a function like this, you want to convert your dict_keys map to a list , then slice that list, and finally join the elements with spaces.要创建这样的函数,您需要将dict_keys映射转换为list ,然后对该列表进行切片,最后将元素与空格连接起来。 Would the below work?下面的工作吗?

def build_sentence(dictionary,size):
  return ' '.join(list(dictionary.keys())[:size])

This is essentially a restatement in function form of @l'mahdi's comment to fit the question format, so go upvote their comment.这本质上是对@l'mahdi 评论的功能形式的重述,以适应问题格式,所以请投票支持他们的评论。

Here's some useful info:这里有一些有用的信息:

https://docs.python.org/3/tutorial/datastructures.html https://docs.python.org/3/tutorial/datastructures.html

https://docs.python.org/3/library/stdtypes.html#dict https://docs.python.org/3/library/stdtypes.html#dict

https://docs.python.org/3/library/stdtypes.html#list https://docs.python.org/3/library/stdtypes.html#list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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