0

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

Ashley
  • 57
  • 2
  • 6
    try this : `print(' '.join(list(my_dict.keys())[:4]))` – I'mahdi Jun 13 '22 at 10:30
  • The simplest way is with a slice (https://stackoverflow.com/questions/509211/understanding-slicing) as suggested above. If you were to write a loop instead you would need to keep track of how many keys you've seen so far (or "enumerate" the loop), add each new key to a collection (e.g. a list) as you go, and "break" out of the loop once you've collected as many keys as you wanted. You could search for how to do those things. – Anentropic Jun 13 '22 at 10:37

1 Answers1

0

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

iteratedwalls
  • 223
  • 1
  • 9