简体   繁体   English

将字典转换为元组并以相反的顺序打印

[英]Convert the dictionary into tuple and printing it in reverse order

I am having values in dict for example {"AR":True,"VF":False,"Siss":True}我在 dict 中有值,例如 {"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").现在我只提取值为 TRUE 的键,所以我只得到 output AR 和 Siss,我正在尝试将这个 output 保存在元组中,现在想以相反的顺序打印出来,例如 ("Siss","AR" )。

Below is my code snippet, When I convert it into tuple its showing me output in form of character instead of string下面是我的代码片段,当我将其转换为元组时,它以字符而不是字符串的形式向我显示 output

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?如何将这些字符更改为单词/字符串?

You can do it easily by transverse the dictionary in reversed order and filter out the non True values.您可以通过以相反的顺序遍历字典并过滤掉非 True 值来轻松完成此操作。

d = {'AR': True, 'VF': False, 'Siss': True}
print(tuple(k for k,v in reversed(d.items()) if v is True))

('Siss', 'AR')

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:它的工作原理是:

  1. reversed -ing the key-value pairs in the dictionary reversed - 字典中的键值对
  2. filter ing the dictionary's items, removing all the key-value pairs that are False . filter字典的项目,删除所有为False的键值对。
  3. Just preserving the key with a map只需使用map保留密钥

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM