Reputation: 1072
I am having values in dict for example {"AR":True,"VF":False,"Siss":True}
Now I am only extracting the keys having value TRUE, so I am only getting the output AR and Siss, I am trying to save this output in tuple and now wants to print them out in reverse order like ("Siss","AR").
Below is my code snippet, When I convert it into tuple its showing me output in form of character instead of string
for i in dic:
if dic[i]==True:
t = tuple(i)
print (t)
Reverse(t)
def Reverse(tuples):
new_tup = tuples[::-1]
return new_tup
How to change those characters into words/strings ?
Upvotes: 0
Views: 638
Reputation: 5479
Here is a simple step-wise approach that uses a list as an intermediate, fills it with the appropriate keys from your dictionary, reverses the list, then converts it into a tuple.
dic = {"AR":True,"VF":False,"Siss":True}
lst = []
for key in dic:
if dic[key]: (# ==True is redundant)
lst.append(key)
lst.reverse()
result = tuple(lst)
print(result)
#('Siss', 'AR')
Upvotes: 1
Reputation: 1147
A functional approach:
dictionary = { "AR": True, "VF": False, "Siss": True }
filtered = filter(lambda kv: kv[1], reversed(dictionary.items()))
just_key = map(lambda kv: kv[0], filtered)
print(list(just_key))
It works by:
reversed
-ing the key-value pairs in the dictionaryfilter
ing the dictionary's items, removing all the key-value pairs that are False
.map
Upvotes: 1
Reputation: 5745
You can do it easily by transverse the dictionary in reversed order and filter out the non True values.
d = {'AR': True, 'VF': False, 'Siss': True}
print(tuple(k for k,v in reversed(d.items()) if v is True))
('Siss', 'AR')
Upvotes: 2