Python: How to create concatenated string from dictionary

I want to pass from a dictionary, for example:

defaultdict(int, {'A': 5, 'B': 4, 'C': 4})

to a list like this:

'A5B4C4'

Is there any short and clever way?

3 answers

  • answered 2020-03-28 10:38 Błotosmętek

    d = defaultdict(int, {'A': 5, 'B': 4, 'C': 4})
    yourstring = ''.join(str(e) for t in d.items() for e in t)
    

  • answered 2020-03-28 10:41 Ch3steR

    You can try this.

    ''.join(k+str(v) for k,v in d.items())
    # 'A5B4C4'
    

  • answered 2020-03-28 11:03 mohammed wazeem

    Another way of doing this is using reduce function from functools

    from functools import reduce
    
    print(reduce(lambda a, b: a + str(b[0]) + str(b[1]), mydict.items(), ''))
    >>>'A5B4C4'
    # reduce takes 3 params (2 required and an optional initializer which is 3rd parameter '' )