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?
You can try this.
''.join(k+str(v) for k,v in d.items())
# 'A5B4C4'
d = defaultdict(int, {'A': 5, 'B': 4, 'C': 4})
yourstring = ''.join(str(e) for t in d.items() for e in t)
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 '' )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.