How to convert my dictionary query to properly formatted string without getting garbage?

Question:

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?

Asked By: Noname

||

Answers:

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)'
Answered By: God Is One
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.