Reversing the key values in a dictionary (advanced reverse string in Python)

Viewed 1226

So what I was trying to do was output the string "33k22k11k", which is just the last value followed by the reversed last key followed by the second last value followed by the second last reversed key and so on. I'm not sure how to get the reversed key value for the specific loop that I am in. From the code I currently I have, I get the output:

dict = {"k1":1, "k2":2, "k3":3}
current=""
current_k=""
for k,v in dict.items():
    for i in k:
        current_k=i+current_k
    current=str(v)+current_k+current
print(current)
print(current_k)

33k2k1k22k1k11k

3k2k1k

5 Answers

Edited

First of all, if you are on python < 3.6, dict does not keep the order of items. You might want to use collections.OrderedDict for your purpose.

d = {"k1":1, "k2":2, "k3":3}
d.keys()
# dict_keys(['k2', 'k1', 'k3'])

whereas,

d = OrderedDict()
d['k1'] = 1
d['k2'] = 2
d['k3'] = 3
d.keys()
# odict_keys(['k1', 'k2', 'k3'])

With our new d, you can either add the key and values and reverse it:

res = ''
for k, v in d.items():
    res += str(k) + str(v)
res[::-1]
# '33k22k11k'

or reversely iterate:

res = ''
for k, v in reversed(d.items()):
    res +=  str(v)[::-1] + str(k)[::-1]
res
# '33k22k11k'

I may be wrong but it seems like you would want to reset the value of current_k each time you access a new key

dict = {"k1":1, "k2":2, "k3":3}
current=""
for k,v in dict.items():
    current_k=""
    for i in k:
        current_k=i+current_k
    current=str(v)+current_k+current
print(current)
print(current_k)

Why not simply do:

print(''.join([a+str(b) for a,b in dict.items()])[::-1])

Output:

"33k22k11k"

But if the values are different from the keys, do:

print(''.join([str(b)[::-1]+a for a,b in dict.items()[::-1]]))

You can do something like this perhaps:

dict = {"k1":1, "k2":2, "k3":3}
print("".join(list(reversed([str(v)+"".join(reversed(k)) for k, v in dict.items()]))))               

Output:

33k22k11k

You can use the Python map function to create the reversed string(using f-string) for each key/value pair and then join it.

dict1 = {"k1":1, "k2":2, "k3":3}
new_dict =  "".join(map(lambda k, v: f'{k}{v}'[::-1] , dict1.keys(), dict1.values()))

Output:

33k22k11k
Related