1

I need to convert the values in dict to comma separated so I can pass it to a dataclass directly.

I referred to - Link & Link

Code:

d = {'Exch': 'N', 'ExchType': 'C', 'Signal': 1660,
     'Price': 207.75, 'date': '/Date(1626690582000)/'}
print(",".join(d.keys()))
print(",".join(d.values()))

But in my case, the keys get printed, but I get an error as below for values (Note: the values in dict are of different data types):

Exch,ExchType,Signal,Price,date
    print(",".join(d.values()))
TypeError: sequence item 2: expected str instance, int found

Pardon if this query is elementary, as am quite new to Python.

iCoder
  • 1,406
  • 6
  • 16
  • 35

1 Answers1

3

It's because the value of the Price key is not a string.

To fix it try a list comprehension:

print(",".join([str(i) for i in d.values()]))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Thanks for that. Sorry, if you don't mind, can you let me know, will the conversion to comma separated maintain the initial dictionary sequence in all cases or will the sequence get distorted after conversion in some cases? – iCoder Jul 19 '21 at 12:24
  • @iCoder Sorry but could you please clarify what you mean by "distorted". – U13-Forward Jul 19 '21 at 12:26
  • You don't need the comprehension with the generator btw, you can just do `print(",".join(str(i) for i in d.values()))` – SimonT Jul 19 '21 at 12:27
  • 1
    @SimonT Well I always go by [this](https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python/9061024#9061024) answer. – U13-Forward Jul 19 '21 at 12:29
  • @U11-Forward by distorted I mean: Eg: expected - N,C,1660,207.75,/Date(1626690582000)/ distorted - N,C,/Date(1626690582000)/,1660,207.75 or 1660,207.75,N,C,/Date(1626690582000)/ – iCoder Jul 19 '21 at 12:31
  • @iCoder You mean disorted? – U13-Forward Jul 19 '21 at 12:33
  • @U11-Forward yes, because I read in this forum in one of the threads, since it is dict, the order cannot be guaranteed. So wanted to be sure when the values are comma separated as above, it does not change the order in some cases – iCoder Jul 19 '21 at 12:35
  • 1
    @iCoder Dictionaries are ordered since Python 3.6 – U13-Forward Jul 19 '21 at 12:36