Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic syntax to concatenate the keys and values of a dictionary

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()
like image 417
pam Avatar asked Feb 07 '14 08:02

pam


People also ask

How do you concatenate a dictionary in a string in Python?

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.


2 Answers

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()))
like image 169
georg Avatar answered Sep 22 '22 01:09

georg


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.

like image 45
falsetru Avatar answered Sep 24 '22 01:09

falsetru