Reputation: 1119
I have a dictionary which may have long values for some key. I want to convert this dictionary to string and send it to a server. But when I am converting it to a string using str(dict) function for the values which have a long value is suffixed with 'L'. This when I am sending it to a server the value it is generating a problem. So can anyone suggest me a easier way of what I can do to avoid the 'L' suffix
Upvotes: 3
Views: 3506
Reputation: 17415
Unrolling gnibbler's code is close to this:
# put all key-value-pairs into a list, formatted as strings
tmp1 = []
for i in D.items()
tmp2 = "{}: {}".format(*i)
tmp1.append(tmp2)
# create a single string by joining the elements with a comma
tmp3 = ", ".join(tmp1)
# add curly braces
tmp4 = "{{{}}}".format(tmp3)
# output result
print tmp4
The inner part of his construction is called a generator expression. They are a bit more efficient, because they don't require the temporary list (or tuple) "tmp1" and allow very terse syntax. Further, they can make code almost unreadable for people not familiar with the construct, if you have that problem try reading it from the inside out. ;^)
Upvotes: 0
Reputation: 5877
I'm not sure what your use case is but to solve this problem and quite possibly the next problem you'll have I'd suggest using json.
import json
a = {'a': 10, 'b': 1234567812345678L}
print json.dumps(a)
# output:
{"a": 10, "b": 1234567812345678}
Upvotes: 3
Reputation: 304137
This is because calling str
on the dict will still call repr
to get the representation of it's contents.
You should just write your own function to iterate over the dict
>>> D = {10000000000000000+n:n for n in range(10)}
>>> print D
{10000000000000000L: 0, 10000000000000001L: 1, 10000000000000002L: 2, 10000000000000003L: 3, 10000000000000004L: 4, 10000000000000005L: 5, 10000000000000006L: 6, 10000000000000007L: 7, 10000000000000008L: 8, 10000000000000009L: 9}
>>> print "{{{}}}".format(', '.join("{}: {}".format(*i) for i in D.items()))
{10000000000000000: 0, 10000000000000001: 1, 10000000000000002: 2, 10000000000000003: 3, 10000000000000004: 4, 10000000000000005: 5, 10000000000000006: 6, 10000000000000007: 7, 10000000000000008: 8, 10000000000000009: 9}
Upvotes: 1