3

I am trying to convert dictionaries into string

for example:

a={3:4,5:6}
s='3 4, 5 6'

The way I am trying is

s=''
i=0
for (k,v) in d.items():
    s=s+str(k)+' '+str(v)
    while i < len(s):
        if s[i]==str(v) and s[i+1]==str(k):
            s+=s+s[i]+','+s[i+1]
1
  • Do you actually want that format? Why? Commented Nov 9, 2016 at 17:04

5 Answers 5

5

Here's a Pythonic way of doing that using a list comprehension:

s = ', '.join([str(x) + ' ' + str(a[x]) for x in a])

Output:

'3 4, 5 6'

Update: As Julien Spronck mentioned, the square brackets ([ and ]) are not necessary. Thus, the following has the same effect:

s = ', '.join(str(x) + ' ' + str(a[x]) for x in a)

Working PythonFiddle

Sign up to request clarification or add additional context in comments.

2 Comments

turns out you type faster ☺
you don't need the square brackets, which would then make a generator expression
3

You can write the list comprehension expression to get the list of key-value string, then join them on , as

>>> d = {3:4,5:6}
>>> ', '.join('{} {}'.format(k, v) for k, v in d.items())
'3 4, 5 6'

OR, even using repr() (Note: it is a hack, I consider .join() approach more pythonic):

>>> repr(d)[1:-1].replace(':', '')
'3 4, 5 6'

Comments

1

I would use the following with a list comprehension:

', '.join([str(k) + ' ' + str(v) for k, v in a.items()])

To illustrate:

In [1]: a = {3:4, 5:6}

In [2]: s = ', '.join([str(k) + ' ' + str(v) for k, v in a.items()])

In [3]: s
Out[3]: '3 4, 5 6'

3 Comments

I actually like this better than my answer since it avoids the awkward use of a[x].
@SumnerEvans I prefer this way as well, but your answer is actually more succinct than mine, and there is certainly something to be said for that. Does yours also perhaps perform better since it doesn't have the extra function call to items()?
Hmm... I'm not sure how dictionaries are stored in the background, I'm assuming they are just a set of tuples, so retrieving them should be fairly efficient, maybe even more efficient than retrieving the keys and then retrieving the values. I'm not familiar enough with the library to say for sure.
1

Of course the most pythonic solution is the one using the list comprehension (see @SumnerEvans and the rest) but just for the sake of having an alternative i will post this here:

a = {3: 4, 5: 6}

v = str(a)
for rep in ['{', '}', ':']:
    v = v.replace(rep, '')
print(v)  # prints -> 3 4, 5 6

Everything can be converted into a string and the manipulated as one. This is what is being done here. From dict to string and then chained replace methods.

2 Comments

Can you speak to the efficiency of this vs list comprehension?
my hunch tells me the list comprehension is much faster but i cannot timeit now since i am at work.. Feel free to try though.
0

You can still have it like this

s=''
i=0
a={3:4,5:6}
for (k,v) in a.items():
    if i < len(a) and s == '':
        s = s + str(k) + ' '+ str(v)
    elif i < len(a) and s != '':
        s += ", " + str(k) + ' '+ str(v)
    i += 1
    print(s)

This should give you

s='3 4, 5 6'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.