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 value
s into strictly formatted string as I need?