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()
Method #2 : Using Counter() + “+” operator In this, the Counter function converts the dictionary in the form in which the plus operator can perform the task of concatenation.
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()))
Using map
with str.join
:
>>> dic1 = {'Name': 'John', 'Time': 'morning'}
>>> '_'.join(map('_'.join, dic1.items()))
'Name_John_Time_morning'
or using generator expression instead of map
:
>>> '_'.join('_'.join(item) for item in dic1.items())
'Name_John_Time_morning'
BTW, dict
is not ordered. So result may vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With