-1
d={'a':'Apple','b':'ball','c':'cat'}

The above dictionary I have and I want my Output like the below-mentioned result

res="a=Apple,b=ball,c=cat"

Is it possible in a pythonic way then please answer it I have tried various method but did not get desired output?

4 Answers4

11

Read your dictionary as key/value pairs (dict.items()) and then just format them in a string you like:

d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}

res = ",".join("{}={}".format(*i) for i in d.items())  # a=Apple,c=cat,b=ball

The order, tho, cannot be guaranteed for a dict, use collections.OrderedDict() if order is important.

zwer
  • 24,943
  • 3
  • 48
  • 66
  • @SamreshKumarJha - Prior to Python 3.6 (at least on CPython) dictionaries were not guaranteed to preserve order. In fact, they are only guaranteed to preserve insert order in CPython implementation of Python 3.6 - interpreter wide guarantee comes only with Python 3.7. Everything not guaranteed to run on CPython 3.6+ or a general Python 3.7+ interpreter should not count on `dict` being ordered. – zwer Apr 06 '18 at 13:39
  • 1
    Slight nitpick: `join` can take a list/tuple comprehension, no need wrap it in an extra layer of parenthesis – af3ld Jul 01 '21 at 15:40
5

One way is to iterate via dict.items and use multiple str.join calls.

d = {'a':'Apple','b':'ball','c':'cat'}

res = ','.join(['='.join(i) for i in d.items()])

# 'a=Apple,b=ball,c=cat'

If you need items ordered by key, use sorted(d.items()).

jpp
  • 159,742
  • 34
  • 281
  • 339
2
def format_dict(d):
    vals = list(d.values())
    return "={},".join(d.keys()).format(*vals) + "={}".format(vals[-1])

d = {'a': 'Apple', 'b': 'ball', 'c': 'cat'}
format_dict(d)  # -> 'a=Apple,b=ball,c=cat'

This joins all the keys into a large string containing replacement fields that we then format passing the dict values as args. There wasn't a trailing replacement field so we concatenate the last value in the dictionary to our large string.

Ryan Marvin
  • 141
  • 1
  • 4
0

For anyone coming here looking for a way to explicitly extract the dictionary keys and values (e.g. if further formatting is required):

d = {'a':'Apple','b':'ball','c':'cat'}
res = ','.join(f'{k}={v}' for k, v in d.items())  
# --> a=Apple, b=ball, c=cat

(uses python 3.6+ f-strings)

rosa b.
  • 1,759
  • 2
  • 15
  • 18