Convert dictionary key tuple to string

Question:

I have a dictionary

dicts = {('name1','name2','name3'): Engineer}

I want to make the key (that is tuple) as one string so my output could look like this:

dicts = {'name1,name2,name3': Engineer}

Any idea?

Asked By: J1701

||

Answers:

Use join() to convert the tuple to a delimited string.

dicts = {",".join(key): value for key, value in dicts.items()}
Answered By: Barmar

You can use str.join.

dicts = {('name1','name2','name3'): 'Engineer'}

new_dct = {}
for k,v in dicts.items():
    new_dct[','.join(k)] = v
    
print(new_dct)

{'name1,name2,name3': 'Engineer'}

Update base comment If you want to use on int/float you can use map(str, tuple).

>>> dicts = {(264.0,264.0,264.0): '264'} 
>>> {','.join(map(str, k)): v for k,v in dicts.items()}
{'264.0,264.0,264.0': '264'}
Answered By: I'mahdi
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.