Skip to content Skip to sidebar Skip to footer

Join Operation For Dictionary In Python

Step 1. i/p= “wwwwaaadexxxxxx” Step 2. converted= {'w': 4, 'a': 3, 'd': 1, 'e': 1, 'x': 6} Step Final. o/p= 'w4a3d1e1x6' I'm on S2 how to go to final step ? Would appr

Solution 1:

You could use a comprehension(But you need to convert those numbers to string), Try code below:

converted = {'w': 4, 'a': 3, 'd': 1, 'e': 1, 'x': 6}
print("".join([str(char) for k, v in converted.items() forcharin (k, v)]))

Solution 2:

You can use itertools.groupby:

from itertools import groupby

ip = "wwwwaaadexxxxxx"
op = "".join(f"{k}{len(list(g))}"for k, g in groupby(ip))
# 'w4a3d1e1x6'

Solution 3:

use Counter

from collections import Counter
ip= "wwwwaaadexxxxxx"print(''.join([i+str(x) for i, x in Counter(ip).items()]))

#'w4a3d1e1x6'

Solution 4:

d = {'w': 4, 'a': 3, 'd': 1, 'e': 1, 'x': 6}
for k,c inzip(d.keys(),d.values()): 
    print(k+str(c),end='')

You can try this, see if it helps

Post a Comment for "Join Operation For Dictionary In Python"