-1

I'm trying to write the key value pairs of the dictionary to a output file without any commas or square brackets.[I have the values as a list.] How can I remove the commas in between the values?

I tried using map() and .join(), but still getting it as:

key1: value1, value2, value3

key2: value1, value2, value3

for keys, values in item_list.items():
    outfile.write("{}: {}\n".format(keys, "".join(map(str, str(values)[1:-1]))))

I expect to be written as,

key1: value1 value2 value3

key2: value1 value2 value3

Julien
  • 13,986
  • 5
  • 29
  • 53
Amravi
  • 11
  • 1
  • Can you post item_list as python formated code? are the values lists? – Frank Oct 22 '19 at 23:18
  • Possible duplicate of [Print a list of space-separated elements in Python 3](https://stackoverflow.com/questions/22556449/print-a-list-of-space-separated-elements-in-python-3) – mkrieger1 Oct 22 '19 at 23:38

2 Answers2

1

I think you are doing a bit too much with your .join() statement. All you need to do is .join() the values with a space.

for keys, values in item_list.items():
    outfile.write("{}: {}\n".format(keys, " ".join(values)))
crookedleaf
  • 2,118
  • 4
  • 16
  • 38
0
"".join(map(str, str(values)[1:-1])))

The reason this doesn't work: to "remove the brackets" you create a single string from the list and take the brackets off of that, then to "remove the commas" you try to make strings out of the list elements and join them up without anything in between. However, since we are already working with a string at this point, the map doesn't iterate over items of the list, but characters of the string.

Trying to remove the brackets doesn't make sense because the list doesn't actually have them - the string used to represent the list does.

To solve this, just do as shown in the other answer: join up the list elements directly. If the elements of the list are not strings, then yes you will need to convert them (so, " ".join(map(str, values))).

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153