-1

I am trying to enumerate a list of of dictionary definitions which are strings and remove the curly braces. The definitions in the list are taken from a json (dictionary api) which is why i am using join to remove the curly brackets.

When I try doing them at the same time it gives a "type error: sequence item 0: expected str instance, tuple found". I have tried joining first and then enumerating but that comes with an error too.

I don't believe I can use a for loop because I am assigning all 3 definitions to a single variable (to use in tkinter) and using a for loop would only show definition 3, also because I am not printing the results.

Example:
definitions = [{definition1},{definition2},{definition3}]

I want to make it so that it shows:

result =  1. definition1
          2. definition2
          3. definition3

I have achieved the same result by doing:

result = "1. " + definitions[0] + "\n" + "2. " + definitions[1] + "\n" + "3. " + definitions[2]

but would rather be able to do it in a way that doesn't require me to type out everything manually
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
Kenneth
  • 21
  • 6

2 Answers2

0

In Python, [{'definition1'}, {'definition2'}, {'definition3'}] is not a list of dictionaries, it is a list of sets.

So first you need to review How to extract the member from single-member set in python? to understand how to get the members out of each set object.

Then you can use the enumerate built-in function to get an iterable matching up objects in the list with their position in the list, an f-string to form each line of the output, a list comprehension to collect the lines into a list, and then string.join() to combine the lines into a single output string:

definitions = [{'definition1'},{'definition2'},{'definition3'}]
out = '\n'.join([f'{n}. {list(d)[0]}' for n, d in enumerate(definitions, start=1)]))
print(out)

Result:

1. definition1
2. definition2
3. definition3
The Photon
  • 1,242
  • 1
  • 9
  • 12
0

use enumerate + join can do the trick


result = ""
for idx, definition in enumerate(defintions):
    result += f"{idx + 1}: {' '.join(definition.values())} \n"

if the definition is a set use

result += f"{idx + 1}: {' '.join(definition)} \n"