Convert dictionary key tuple to string

Viewed 80

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?

2 Answers

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

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

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'}
Related