2

Question

The goal is to find a simple way for converting a set of data to a string.

Maybe I am too newby but I found nothing about conversion from a set to string. A similar question (Numpy converting array from float to strings) did not help me a lot.

Example

The code I wrote seems definitely not ideal:

DataSet = {(1,4): 272.3,
           (2,4): 274.74}
print(', '.join(np.array(DataSet).astype('str'))))

Personal goal

In the end I want to create a string like:

DataSet = {(1,4): 272.3,
           (2,4): 274.74}
version = 2.7
print(''.join(np.array(['The data in {',
                        ', '.join(np.array(DataSet).astype('str'))),
                        '} is calculated with python%3.1f.' % version]))

The output should look like (it would be nice but not necessary to implement some fixed float precision):

'The data in {272.3, 274.7} is calculated with python2.7.'
Community
  • 1
  • 1
strpeter
  • 2,562
  • 3
  • 27
  • 48
  • `', '.join(str(i) for i in DataSet.items())`? how about `str(dataSet)`? Do you actually need to convert the individual elements, or do you only need a single string output (and if the latter, what's the desired output format for the dict?)? – Henry Keiter Dec 11 '14 at 18:46
  • Sorry, I couldn't understand your problem. Can you give a sample input/output? – late_riser Dec 12 '14 at 04:22
  • @HenryKeiter: The first of your statements returns: `'((2, 4), 274.74), ((1, 4), 272.3)'`, and the second one: `'{(2, 4): 274.74, (1, 4): 272.3}'`. I did not expect the index to be printed too - but it makes sense in most cases! Do we call the structure of `DataSet` set or dictionary? @late_riser: I hope having clarified the desired output. – strpeter Dec 12 '14 at 08:42

1 Answers1

1

DataSet is a Python dictionary and thus DataSet.values() returns the list of its values. The string you need can be generated by ', '.join(map(str, DataSet.values())) or ', '.join(str(v) for v in DataSet.values()).

davidedb
  • 867
  • 5
  • 12