Home > Net >  Convert dictionary key tuple to string
Convert dictionary key tuple to string

Time:07-24

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?

CodePudding user response:

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

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

CodePudding user response:

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