Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: how convert my dictionary query to properly formatted string without getting garbage?

Assume this is my dictionary:

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

I need cut out 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 noob in 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 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?

>Solution :

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:

as commented by @flakes

You can try:

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

for single value:

#'(4)'

for multiple values:

#'(4, 5, 7)'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading