1

I am trying to convert a python dictionary to one string Example:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

should be

key1=value1; key2=value2; key3=value3

I tried to search for such a topic but didn't find any clue

This is my try but I am seeking to learn

tmp = ''
for cookie in cookies_dic:
    tmp = tmp + ';' + cookie + '=' + cookies_dic[cookie]

print(tmp[1:])
YasserKhalil
  • 9,138
  • 7
  • 36
  • 95
  • But what did you try kwa code? – 0stone0 Mar 30 '22 at 16:27
  • 2
    `'; '.join(f'{k}={v}' for k, v in dct.items())`? – Axe319 Mar 30 '22 at 16:27
  • 1
    In Python 3.6+ (b/c of f-strings), for a dictionary `d`: `'; '.join([f"{k}={v}" for (k,v) in d.items()])`. The same general idea could be used for older python versions replacing the f-string interpolation with, e.g. `%` interpolation. Also note, you actually _do_ want to explicitly create a list here instead of just passing `join` a generator (without `[`,`]`). – jedwards Mar 30 '22 at 16:27
  • @jedwards no need for an intermediate `list`. You can just hand `str.join()` a generator expression. – Axe319 Mar 30 '22 at 16:30
  • I already did my attempt. But I am seeking to learn new techniques – YasserKhalil Mar 30 '22 at 16:32
  • 1
    @Axe319, I knew someone was going to say that -- I just updated my comment to make it clear that you _do_ want an explicit list and not just the generator. See [this](https://twitter.com/raymondh/status/1374826259482439681), the comment [here](https://stackoverflow.com/questions/14447081/python-generator-objects-and-join), [this](https://news.ycombinator.com/item?id=26148197), etc. – jedwards Mar 30 '22 at 16:32
  • 1
    @jedwards good point. I did not know that. I'll have to start following Hettinger. – Axe319 Mar 30 '22 at 16:35
  • 1
    What's wrong with `repr(cookies_dic)`? – Mark Ransom Mar 30 '22 at 16:41
  • @MarkRansom What does this line do? – YasserKhalil Mar 30 '22 at 17:17
  • Try it and find out. – Mark Ransom Mar 30 '22 at 17:47
  • I already tried before asking the question. It returns the same dictionary as output – YasserKhalil Mar 30 '22 at 17:55

2 Answers2

1

use this code

t = []
for i in d:
   t.append(f"{i} : {d[i]}")  
s = " ;".join(t)
print(s)
0
d={'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
result=''
for i,j in d.items():
     result+=i+'='+j+';'
print(result)

key1=value1;key2=value2;key3=value3;
zeeshan12396
  • 382
  • 1
  • 8