Pythonic syntax to concatenate the keys and values of a dictionary

dictionary, python

Solution

I like comprehensions better

result = '_'.join(x + '_' + y for x, y in dic1.items())

or

result = '_'.join('{}_{}'.format(*p) for p in dic1.items())

The latter form also works when there are non-string keys or values.

To ensure the output is sorted,

result = '_'.join('{}_{}'.format(*p) for p in sorted(dic1.items()))

Problem

I have a dictionary similar to this one ``` dic1 = {'Name': 'John', 'Time': 'morning'} ``` I want to concatenante the keys and values with a "_" separator with the following schema: ``` Name_John_Time_morning ``` This is equivalent to key1_value1_key2_value2 I have tried the following line of code but without success ``` x + "_" + v for x,v in dict1.keys(), dict1.values() ```

Original source