0

Assume this is my dictionary:

dc = { 0 : { "name" : "A", "value" : 4}, 1 : {"name" : "B", "value" : 5}, 2: {"name" : "C", "value" : 7}}

I need to transform all values from keys value into a string formatted like this:

(4, 5, 7)

Format is mandatory (this is some robotic automation) - series of integers, separated by , and surrounded by (). No other garbage.

Good examples:

()
(1)
(1, 5, 15, 37, 123, 56874)

Bad examples:

[4, 5, 7]
{4, 5, 7}
('4', '5', '7')
(1,)

My naive approach was "lets iterate over all dictionary items, collect all "values" into tuple and then str it", but tuples cannot be modified. So I said "ok, collect to list, convert to tuple and then str":

res = list()
for item in dc.values():
    res.append(item['value'])
print(str(tuple(res)))

I'm new to Python and I bet there is more elegant way of doing this, but it worked fine for multi-item and empty results. However, if my query returns only single item, then Python adds an extra empty item and it breaks the robotic client.

>>>>str(tuple([4]))
(4,)

Is there way of not getting this empty extra without explicit checking if len(res)==1?

Actually, is there more robust and elegant way of cutting out all values into strictly formatted string as I need?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Noob
  • 335
  • 1
  • 8
  • 2
    I see this was closed for being a duplicate even though the other question doesn't exactly answer yours. To properly format it no matter the number of elements, you can use an f-string and some python black magic to join all the elements with commas and surround with parentheses: `f'({", ".join(map(str, res))})'` – Adid Jan 25 '23 at 05:44
  • @Adid I'm looking for a duplicate target which answers the string joining part of the question; it is better to close such questions sooner rather than let them accrue many duplicated answers. – kaya3 Jan 25 '23 at 05:48
  • Yes someone closed just by judging by title, without getting into details. God bless fast bashing admins. – Noob Jan 25 '23 at 05:49

1 Answers1

-1

You can use one line generator:

tuple(item['value'] for item in dc.values())
#(4, 5, 7)

If you just have 1 value you can add [0] at the end:

tuple(item['value'] for item in dc.values())[0]
#4

Else you will get like:

(4,)

If you have 1 value and you want string datatype then:

str(tuple(item['value'] for item in dc.values())[0])
#'4'

Edit:

You can try:

'(' + ', '.join(str(item['value']) for item in dc.values()) + ')'

for single value:

#'(4)'

for multiple values:

#'(4, 5, 7)'
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44