Reputation: 47
I need to create one line string with dictionary's keys in Python3. I can print them in one line with end='' function but i can't update like that.
I have a dictionary like below.
array = {
'MERCHANT': "TEST",
'ORDER_REF': "Test123",
'BACK_REF': "http://2ac99X37.ngrok.io/",
'ORDER_PNAME[0]': "BLA",
'ORDER_PCODE[0]': "BLA",
'ORDER_PINFO[0]': "BLA",
'ORDER_PRICE[0]': "1",
'ORDER_VAT[0]': "18",
}
And i'm sorting them to their keys and getting length
for k, v in sorted(array.items()):
hashstring =str(len(v)) + str(v)
But when i print the hashstring at this step, they printing like below
25http://2ac99X37.ngrok.io/
4TEST
3BLA
3BLA
3BLA
11
7Test123
218
I need to update them like below because true hash calculation
25http://2ac99X37.ngrok.io/ 4TEST 3BLA 3BLA 3BLA 11 7Test123 218
Like i was mentioned above; I can print them in one line with end='' function but this is not effecting the "hashstring" parameters value.
My hash calculation code is like below.
signature = hmac.new(secret.encode('utf-8'), hashstring.encode('utf-8'), hashlib.md5).hexdigest()
Could you please assist me ?
Best,
Upvotes: 0
Views: 920
Reputation: 5613
You need to initialize hashstring
before your loop, then keep concatenating to it in your loop, as the following:
hashstring = ''
for k, v in sorted(array.items()):
hashstring += '{}{} '.format(len(v), v)
hashstring = hashstring[:-1] # to remove the trailing space
Output:
25http://2ac99X37.ngrok.io/ 4TEST 3BLA 3BLA 3BLA 11 7Test123 218
or you can use list comprehension instead of the loop to do it in one line as the following:
hashstring = ' '.join(['{}{}'.format(len(v), v) for k, v in sorted(array.items())])
Upvotes: 1
Reputation: 3195
Your code isn't properly formatted.
I think the issue is in your for loop.
If you write hashstring =str(len(v)) + str(v)
it will represent a different value every time you print it.
Try
hashstring=''
for k, v in sorted(array.items()):
hashstring += str(len(v)) + str(v)
print(hashstring)
Upvotes: 0
Reputation: 96171
Whenever you want to want to combine many individual strings into one string with a separator, you want to use .join
. So, accumulate your parts into a list, then .join
them:
In [6]: hashparts = []
In [7]: for k, v in sorted(array.items()):
...: hashparts.append(str(len(v)) + str(v))
...:
In [8]: hashstring = ' '.join(hashparts)
In [9]: print(hashstring)
25http://2ac99X37.ngrok.io/ 4TEST 3BLA 3BLA 3BLA 11 7Test123 218
Upvotes: 0