简体   繁体   中英

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

Here's some useful info:

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#list

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